Pages

Wednesday, March 16, 2011

Stumbling around Google collections

I came across a situation in some code I need to modify where maps were being 'filtered' to create tailored data for different situations. I couldn't come up with the solution I wanted in the moment so I cobbled up an example to see what might work.


As a simple example:


We're looking at two different criteria (string starts with a vowel or a consonant) and two different targets -- the map key or the value.

The looping is duplicated and the determination of whether the values should be in the new map screams for a predicate.

In Google collections this is usually just a filter taking in the collection and the predicate. But 'filter' wasn't available on a Map -- it works on a collection.

Well, first I needed a predicate:


That was easy enough.

My first try was to filter the entry set of the map and then add the filtered elements to the result:


Not too happy that I'm looping over something twice in the worst case.
Well, I can just use the predicate without using anything else from Google collections:


But, I just felt there should be a better way. Asked a couple of people while I was trying different searches. Finally I found that Maps has a tranform, but it also has different filter methods! Just what I needed.

The one-liner:


That will wrap it up for now.

No comments:

Post a Comment