A new version of the Guava library was released earlier this month and contains several new features and improvements.
Here is an overview of some of the significant API additions in this release:
1. Escapers
Escapers
allow you to "escape" special characters in a string in order to make the string conform to a particular format. For example, in XML, the <
character must be converted into <
for inclusion in XML elements. Guava provides the following Escapers:
Escaper
. Here is an example of various Escapers
in action:
// escaping HTML HtmlEscapers.htmlEscaper().escape("echo foo > file &"); // [result] echo foo > file & // escaping XML attributes and content XmlEscapers.xmlAttributeEscaper().escape("foo \"bar\""); // [result] foo "bar" XmlEscapers.xmlContentEscaper().escape("foo \"bar\""); // [result] foo "bar" // Custom Escaper // escape single quote with another single quote // and escape ampersand with backslash Escaper myEscaper = Escapers.builder() .addEscape('\'', "''") .addEscape('&', "\&") .build();
2. StandardSystemProperty
StandardSystemProperty
is an enum of Java system properties such as java.version
, java.home
etc. The great thing about this is that you no longer need to remember what the system properties are called because you simply use the enum! Here is an example:
StandardSystemProperty.JAVA_VERSION.value(); // [result] 1.7.0_25 StandardSystemProperty.JAVA_VERSION.key(); // [result] java.version
3. EvictingQueue
The EvictingQueue
is a non-blocking queue which removes elements from the head of the queue when it is full and you attempt to insert a new element. Example:
// create an EvictingQueue with a size of 3 EvictingQueue<String> q = EvictingQueue.create(3); q.add("one"); q.add("two"); q.add("three"); q.add("four"); // the head of the queue is evicted after adding the fourth element // queue contains: [two, three, four]
4. fileTreeTraverser
As its name suggests, Files.fileTreeTraverser
allows you to traverse a file tree.
FluentIterable<File> iterable = Files.fileTreeTraverser().breadthFirstTraversal(new File("/var/tmp")); for (File f : iterable) { System.out.println(f.getAbsolutePath()); }
(Note: Java 7's Files.walkFileTree
also traverses a file tree and I showed you to use it in one of my earlier posts: Java 7: Deleting a Directory by Walking the File Tree. I'd recommend this approach if you are using Java 7.)
The full release notes of Guava 15 can be found here.