Filtering and Transforming with Guava

In ruby, you can do operations on collections really easily. For instance, to convert an array of words to all uppercase, you can simply do

 ["foo1", "foo2", "foo3"].map {|w| w.upcase }

Java on the other hand is lacking in this regard. I set out to find a better way to manage these types of transforms in my java code, and wound up looking at Guava (nee Google Collections). Way back, a coworker (Dain Sundstrom) had shown me some great usage of the filtering abilities of the Google Collections, and I decided to take another look (’cause it’s been a while, and I forget things easily)

First, I defined the transformation I wanted to use

public class Transformers {

    public static Function Upcase = new Function() {
        @Override
        public String apply(final String from) {
            checkNotNull(from);
            return from.toUpperCase();
        }
    } ;
}

Then I actually use it (or define the transformation inline as per the second example)

   public static void main(final String[] args){

        List myList = new ArrayList();
        myList.add("foo1");
        myList.add("foo2");

        //now let's transform them
        List upcasedList = transform(myList, Transformers.Upcase);

        System.out.println(Joiner.on(", ").skipNulls().join(upcasedList));

        //If you want to be ruby/closure like, then try this with an inline def
        List downList =  transform(myList, new Function() {
            @Override
            public String apply(final String from) {
                return from.toLowerCase(); 
            }
        } );

        System.out.println(Joiner.on(", ").skipNulls().join(downList));
}

Simple enough once you get your head around it, but sadly, it’s not nearly as succinct or nice to look at.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.