Friday, August 26, 2011

Guava's Collections...

Oh the names developers come up with...

Guava is the new name for the amalgamated set of lightweight java libraries google has produced. It includes what used be google collections.

In a nutshell, guava's collections are commons collections built with 1.5 language features. Generics and other syntactic sugar.

If you're a java developer and haven't seen them or are not using them, then you're wasting a lot of time.

Especially in testing.

You need to create a small list, of say, 3 elements to pass into a SIT.

Typical solution:

List list = Arrays.asList(new Object[]{"1", "2", "3"});
Solution when using guava:

Lists.newArrayList("1", "2", "3");
 Eminently more readable, succinct and to the point.

The other useful commons collections features are also supported... e.g. filtering.

One example I'll supply is a filter which submits to the generic type:

example...


    public Iterable getSquares() {
return Iterables.filter(shapes, Square.class);
    }

With a more ordinary filter, the return type of the filter would have to be the same as the type that is passed in (in this case the shapes collection). Not with this funky mechanism. Unfortunately, guava does not have the same feature when working with sets and lists. I guess you could just wrap this Iterable in a set, but that would mean having to iterate over the collection up front.


No comments:

How important is the programming language?

  Python, typescript, java, kotlin, C#, .net… Which is your technology of choice? Which one are you currently working in and which do you wa...