Posts Tagged ‘guava’

Guava: Google Libraries for Java

Wednesday, October 7th, 2009

Guava is a set of Java Libraries recently provided by Google. The API reference for it is located here, but I’ll provide a very, very brief overview of some of the classes provided. These libraries aren’t at a release version yet, but they still seem quite usable.

CharMatcher - An instance of CharMatcher represents a set of matching characters. You can use predefined constanc CharMatchers, such as CharMatcher.WHITESPACE or CharMatcher.WHITESPACE, or you can also use a factory method, such as CharMatcher.oneOf(”ABC”). Alternatively, you could subclass CharMatcher and implement matches(char c). Operations on a CharMatcher represent what you want done for characters that are matched by the CharMatcher for a string. Some of these are matchesAllOf, removeFrom, and retainFrom. For more examples, see the Guava API documentation.

Charsets - predefined constants for charsets supported on all JVMs (for example, UTF-8) which do not need UnsupportedEncodingExceptions.

Joiner - this class joins pieces of text with a separator. Works on arrays, Lists, and Maps. This

Splitter - Much better than String.split, constructing on and using the split( String s ) method will return an iterator over the pieces of the string. It can be configured for how you want to handle empty pieces, unlike the String.split method. You can also split on strings that are not regular expressions, and are not required to have an array.

Guava also has a set of classes for utilities on primitive objects. They give primitives hashCode, compare, and many other methods for primitives. They also provide an asList method that allows viewing an array as a List. Another feature is utilities for dealing with both signed and unsigned bytes. For more of the details, check out either the API documentation or the introductory PDF.

Guava also provides a set of classes for dealing with IO. There are utility methods for Streams, Files, and other IO classes. One of the notable standouts here is the Files.readLines method(). There are two methods with this name: one takes a File and a CharSet and returns a List containing the file. The other method also takes a LineProcessor class, which is an interface containing processLine(String) and getResult(). Each line will be called with processLine(String), and the once all the lines have been processed the result of getResult() will be returned.

Guava also provides a set of utilities for concurrency. I haven’t done very much with concurrency, so I can’t really talk about these much. I’d suggest looking them over yourself and seeing if there’s anything you can use. I’ll definitely come back and check out what they have when I have some program that needs to have concurrent threads.