1. Concise collection initialization - No example of Java being overly verbose is complete without showing a repetitive and noisy constructor like this:
Java 7 intends to introduce a "diamond operator" which allows the code to be converted to this:
This kind of change probably won't prevent any bugs, but in my opinion it greatly reduces code "noise". Noise does not matter in a single-line example, but makes a big difference when multiplied across an entire system.
Google Guava provides similar functionality, today, and it works all the way back to Java 5. It takes advantage of one of the few places Java does infer types: method return values.
Here, newHashMap is a static method on com.google.common.collect.Maps, with a static import. It gets better, Guava can also be used to initialize collections with values:
java.util.Arrays.asList does something similar, but is actually immutable. In combination with other techniques (many from Guava), type inference for collections and easy collection initialization can really clean up your code.
2. Multimap - How often are the values in your map actually a collection? Imagine taking a group of people and grouping these people by last name using a Map.
Here's a small sampling of clever utility methods provided:
I've got to stop here, or I'll never finish. I have only covered a few of the classes I really love, honorable mention goes to:
- BiMap - Easily create the inverse of your map (keys become values and values become keys)
- Ordering - Lots of nice extensions to Comparator
- MultiSet - A set that keeps count of duplicates
- Predicates and Functions - reusable objects for filtering and transforming your collections
- AbstractIterator - Writing your own iterator is annoyingly tricky - this can really help
- Forwarding Collections - Makes it easy to write your collection classes by delegating to existing collections classes (w/o boilerplate)
- MapMaker - Factory for producing maps for caches - makes a very tricky job easier.
- Immutables - I'm a big fan of immutability, but haven't investigated Guava's extensive support for it yet