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
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
repeat() useful while you’re looking around the
Preconditions provides convenient ways to test arguments and throw illegal argument exceptions when necessary. There’s also
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
boolean targetIsInArray = Ints.contains(int array, int target)
Not earth-shattering, but again, very convenient.
Floats, etc.) also has
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.