131

I have had a quick scan of the Guava API and the new collection types it provides(Multimap and BiMap for example appear useful) and I am thinking of including the library in the project(s) I work on.

However, I also have a reticence to include libraries willy-nilly if they are of no great benefit and learning the features wastes valuable time.

Have you included the Guava library in your project and has it proved useful in any unexpected way? Would you always use it in the future? What has been its main benefit/time saver? What are its hidden features?

3
  • 4
    Your title and your question doesn't really match.
    – aioobe
    Sep 21, 2010 at 10:41
  • 4
    "the new collection types... appear useful" and "I have a reticence to include libraries ... if they are of no great benefit" - well which is it then? you either think the library is useful and has benefit or you don't
    – matt b
    Sep 21, 2010 at 11:41
  • 1
    As of 2017 (question now closed), if you are using the latest Gradle (4.4.1) guava 21.0 is added to build.gradle by default as a dependency, with the words "This dependency is used internally, and not exposed to consumers on their own compile classpath", suggesting that the Gradle team have decided there's some really valuable stuff in there. Jan 2, 2018 at 7:25

8 Answers 8

159

Seriously, everything in Guava is useful. I've been using it for quite a while, and am still always discovering something new I can do with it that takes less code than doing it by hand.

Some things others have not really mentioned that I love:

  • Multimaps are just great. Any time you would use something like Map<Foo, Collection<Bar>>, use a multimap instead and save yourself a ton of tedious checking for an existing collection mapped to a key and creating and adding it if it isn't there.
  • Ordering is great for building Comparators that behave just how you want.
  • Maps.uniqueIndex and Multimaps.index: these methods take an Iterable and a Function and build an ImmutableMap or ImmutableListMultimap that indexes the values in the Iterable by the result of applying the function to each. So with a function that retrieves the ID of an item, you can index a list of items by their ID in one line.
  • The functional stuff it provides... filter, transform, etc. Despite the verbosity of using classes for Functions and Predicates, I've found this useful. I give an example of one way to make this read nicely here.
  • ComparisonChain is a small, easily overlooked class that's useful when you want to write a comparison method that compares multiple values in succession and should return when the first difference is found. It removes all the tedium of that, making it just a few lines of chained method calls.
  • Objects.equal(Object,Object) - null safe equals.
  • Objects.hashCode(Object...) - easy way to get a hash code based on multiple fields of your class.
  • Objects.firstNonNull(Object,Object) - reduces the code for getting a default value if the first value is null, especially if the first value is the result of a method call (you'd have to assign it to a variable before doing this the normal way).
  • CharMatchers were already mentioned, but they're very powerful.
  • Throwables lets you do some nice things with throwables, such as Throwables.propagate which rethrows a throwable if it's a RuntimeException or an Error and wraps it in a RuntimeException and throws that otherwise.

I could certainly go on, but I have to get to work. =) Anyway, despite my having listed some things I like here, the fact is that everything in Guava is useful in some situation or another. Much of it is useful very often. As you use it, you'll discover more uses. Not using it will feel a bit like having one hand tied behind your back.

1
  • 2
    Totally agree on ComparisionChain. Sep 29, 2010 at 23:59
45

I've been effectively using Guava for a couple of years, inside Google - and it's wonderful.

The parts I'm particularly fond of are:

  • Charsets.* - so simple, so useful
  • Collections
  • IO handling (read a resource completely in a single line, etc)
  • Splitter/Joiner
  • Preconditions
2
  • 6
    Note that we now have StandardCharsets in Java 7+. I wonder how many other of Guava's features have found their way into Java.
    – user201891
    Mar 22, 2016 at 23:32
  • 2
    I found this Modernizer Maven Plugin which detects uses of legacy APIs, including third-party libraries like Guava. The configuration file appears to contains 67 Guava deprecations, including StandardCharsets.
    – user201891
    Nov 1, 2016 at 21:08
28

I initially used it for collections shorthands. For example, instead of:

Map<String, Map<Long, List<String>>> map = new HashMap<String, Map<Long, List<String>>>();

you can do this:

Map<String, Map<Long, List<String>>> map = Maps.newHashMap();

It's also easy to populate maps:

ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");

Now, I have discovered some other useful utilities present in Guava. For example, the CharMatcher class allows you to match sequences of characters. You can do:

CharMatcher.inRange('a','z').or(inRange('A','Z'));

or

String phoneNumber = CharMatcher.DIGIT.retainFrom("my phone number is 123456789");
21

CharMatcher's precomputed() method (source) is a nice "hidden feature" I stumbled upon the other day.

It's really just an optimization, that creates a lookup table (using a bit array), and then simply looks up characters to see if they "match".

It's the kind of hidden optimization you can leverage when you use a library, that you might not have thought of yourself in your own code.

Of course, if you create a complex CharMatcher, which you plan to use many times, you must remember to call the precomputed() method, like:

CharMatcher complexMatcher = CharMatcher.anyOf("cat")
                                        .or(CharMatcher.DIGIT)
                                        .or(CharMatcher.WHITESPACE)
                                        .precomputed();
1
  • I also have question on guava ListenableFuture. If possible can you review my design and help me clarify some of my doubts and how I should deal with them? I recently started working with Guava ListenableFuture and I like a lot but having some confusion regarding how to use them efficiently.
    – john
    Mar 30, 2015 at 4:48
17

Here's a YouTube video from Google (speaker: Kevin Bourrillion, lead engineer for Google's core Java libraries) which shows the beauty of Google Collections. One thing Google did, which I believe is brilliant, is guarantee Immutability in collections.

12

Google Guava is a utility library, so I doubt that there is a killer class inside it. The whole things about utility is you almost use that in every projects you have. I can't remember any project I've done that doesn't use Java collection. And truth is, the collection utility of Google Guava is wonderful and should be in the Java SDK itself.

I've written three articles about classes on Google Guava:

And this is not all, there are many other things you can do with Guava.

8

Absolutely very super useful. It's almost invariably the first library added to a new project.

  1. We're very fond of Iterators/Iterables and the Function interface.
  2. The Service family of interfaces are great abstractions
  3. We're so committed we've started to use the ImmutableXXX classes our API types to communicate that it can't be changed.
  4. Computing maps (from MapMaker) are wonderful in certain situations.

Overall, the library is very high quality. The API is well thought out, the implementation solid. Highly recommended.

7

MapMaker now offers bounded LRU caches - that's some substantial machinery hidden behind a tiny API. This has the potential for huge utility, and I'm still all over the code.

Not the answer you're looking for? Browse other questions tagged or ask your own question.