Google’s guava java: the easy parts

Google’s guava is one of the best, most useful all-purpose java libraries to come out in a long time. It’s surprising that it isn’t standard in most projects now. Maybe there’s too much in there. If the functional and concurrency packages seem like too big an investment of time to understand and use in your code, just focus first on the easy parts. Think of guava as the next generation of apache commons utilities, with lots more stuff if and when you want to explore it.

Here are some of my favorite simple, yet handy routines in guava:

List<String> lines = Files.readLines(file, charset);

This is the same as FileUtils.readLines() in apache commons io, but updated to use generics. Files doesn’t quite have all the things that FileUtils has, but there are many other helpful methods like deleteRecursively(), createParentsDir(), and move().

boolean isEmpty = Strings.isNullOrEmpty(yourString);

You’ve probably written something like this already, perhaps even several versions scattered in different projects. Why not just use one from an established api? You might also find emptyToNull() or repeat() useful while you’re looking around the Strings class.

Preconditions.checkArgument(boolean expression);

Preconditions provides convenient ways to test arguments and throw illegal argument exceptions when necessary. There’s also checkNotNull(), checkState(), etc.. If your code handles validating arguments haphazardly, preconditions can be a standard, concise way to deal with them.

Map<String, Date> sampleMap = Maps.newHashMap();

Try creating your generic collections without having to duplicate the generic types and you won’t want to go back. Joshua Bloch helped design guava’s collections package so it might as well be part of the official java collections api now.

String relativeFilePath = Joiner.on("/").join(filePieceArray);

Joiner feels so natural to use. It’s quite handy for making file paths, comma-separated string lists, etc. without worrying about that trailing separator. Guava’s splitter also has nice advantages over String.split().

boolean targetIsInArray = Ints.contains(int[] array, int target)

Not earth-shattering, but again, very convenient. Ints (and Doubles, Floats, etc.) also has concat(), lastIndexOf(), and other methods that let you deal with arrays as a whole without manually iterating through them to find what you want.

The guava api is just fun to browse. Its methods are intuitive to use and understand, and once you’ve got guava on your classpath, they might also be gateway drugs to guava’s more advanced features. But you can just stick with the basics if you want. They’re worth it on their own.

This entry was posted in java, software and tagged . Bookmark the permalink.

11 Responses to Google’s guava java: the easy parts

  1. Nice! I also think Guava has received far too little attention. I’ve collected some more resources on Guava here if anyone wants:

    http://blog.tfnico.com/2010/06/some-google-guava-resources.html

  2. Pingback: Useful Guava Tips and Tricks « Scotsman on a Horse

  3. kamel says:

    Guava has one main disadvantage, which is mentioned in the project main site:

    “All APIs marked @Beta at the class or method level are subject to change”

    Provided that quite a lot of classess and methods are annotated as @Beta (whole packages .net.*, .io.*, .util.concurrent.*) – one wouldn’t like to risk depending a big project on an unstable library and have to support the library on its own, once anything changes in new version. The risk is too big, business won’t bear it (if I were a PM – I wouldn’t).

    • tborthwick says:

      That’s a good point. I think Files is the only example I gave that’s still Beta, but it’s something to be aware of. The mix of beta and production is probably an argument that Google should have kept these apis separated into different projects. However, I would say that developers, even at corporations, do sometimes rely on pre-production software depending on a number of factors: where and how your project is used, how much confidence you have in the creator, the quality of your tests, etc. Different environments have different standards, too. If your shop downloads jars from a maven repo or code from github without worrying too much about its provenance, google’s beta code may well be better tested than what you already use. If you’re in a tight, FDA-regulated shop, you’ll want to stick with fully trusted production components and wait until the beta tag on those apis is taken off (hopefully soon.)

      • kamel says:

        I was thinking more of a code that is developed with intention to last for years and necessity to be maintained – in this situation, from business perspective, you can’t risk instability of its components.

        But for ad-hoc and small projects – this can be a very nice time-saving library.

        • Gili says:

          I disagree. Just because it’s marked @Beta does not mean it’s unstable. Just because the API may change in the future does not mean that your already-deployed code will stop working.

          Frankly, I’d much rather use a clean, well-maintained API that changes over time than feel “secure” using a poor API that leads to hard-to-maintain code. Ask yourself how much time you spend fixing bugs versus adapting to changed APIs.

    • meh says:

      you certainly sound like a PM.

      You don’t have to update your guava version, this is really a moot point.

      And if you every really want to get the leatest and greatest, then you’re project should be well tested enough to handle something trivial like a joiner which changed its api.

  4. Pingback: Daily del.icio.us for October 11th through October 17th — Vinny Carpenter's blog

  5. I think some of you might be reading a little too much into the @Beta tag. It simply means that the API might change later. That’s usually not too hard to deal with when it happens. It doesn’t mean the code is untrusted and unsafe — remember, Google uses this stuff itself in production — a lot.

    Also, @Beta is only on a minority of the APIs; a sizable minority, but the comments above make it sound more prevalent than it is. In particular, very little of com.google.common.collect, the largest package, is beta.

  6. Nice post. I learn something new and challenging on sites I stumbleupon everyday.
    It’s always useful to read articles from other authors and practice a little something from their sites.

  7. Meine Seite says:

    An outstanding share! I have just forwarded this onto a colleague
    who had been conducting a little research on this.
    And he actually bought me dinner due to the fact that I found it for him…

    lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanks for spending time to discuss this issue
    here on your blog.

Leave a Reply

Your email address will not be published. Required fields are marked *