Google Guava

Google started releasing some internal Java code as open-source under the name Google-collections. This became much more than only collection support and was rebranded as guava.

Guava contains a lot of extremely useful code.

It adds a bunch of very useful Collection-related classes and interfaces:

  • Collections2` - Utility methods for filtering, transforming, and getting all possible permutations of Collections.
  • BiMap` - A Map that goes both ways (one-to-one mapping where values can map back to keys).
  • Multimap` - A Map that can associate keys with an arbitrary number of values.
  • Multiset` - A set that also keeps tracks of the number of occurances of each element.
  • Table` - Uses a row and column as keys to values.

For every Collection type, it also has a static utility class with useful methods, for example:

  • Lists: newArrayList, asList, partition, reverse, transform`
  • Sets: newHashSet, filter, difference, union`
  • Maps: newHashMap, newTreeMap, filterKeys, filterValues, asMap`

It also contains some concurrency support, such as the following:

ListenableFuture

A ListenableFuture allows you to register callbacks to be executed once the computation is complete, or if the computation is already complete, immediately. This simple addition makes it possible to efficiently support many operations that the basic Future interface cannot support.

~~~~~~~~~~

ListeningExecutorService srv = MoreExecutors

.listeningDecorator(Executors.newFixedThreadPool(10));

ListenableFuture<Rocket> rocket = srv.submit(new Callable<Rocket>(){

  public Rocket call() {

    return launchIntoSpace();

  }

});

Futures.addCallback(rocket, new FutureCallback<Rocket>() {

  // we want this handler to run immediately after we launch!

  public void onSuccess(Rocket rocket) {

    navigateToMoon(rocket);

  }

  public void onFailure(Throwable thrown) {

    launchEscapePod();

  }

});

~~~~~~~~~~

Guava also contains tons of helpful utilities for general software development, such as the following:

EventBus

Allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other).

CacheBuilder

Builds caches that can load and evict values. Caches are tremendously useful in a wide variety of use cases. For example, you should consider using caches when a value is expensive to compute or retrieve, and you will need its value on a certain input more than once.

BloomFilter

Bloom filters are a probabilistic data structure, allowing you to test if an object is definitely not in the filter, or was probably added to the Bloom filter.

Guava has great documention available on the [google-code wiki].

Tags: java code guava