Groovy #4 – A list of map of lists OLC

Find key by value in a map with a list of values

One of the greatest assets of Groovy syntax is how easy it makes to manipulate lists and maps. In fact, the second most clumsy part of Java syntax and implementation are the Collections. The Calendar takes the honors. Collections are functional, but very cumbersome and laborious to implement, ie when compared to Groovy. Even if one is hesitant to learn functional programming or succumbing to the Obsessive Closure Designer syndrome, it is illustrative to know how easy it is to manipulate collections in Groovy.

def mapOfListValues = [a:[1,2], b:[3,4], c:[5,6], d:[7,8]]

So find the key to which a given number belongs to and return a default value if not found.

def findKey = { value -> (mapOfListValues.find { value in it.value }?.key)?:'Not Found' }
assert findKey(3) == 'b'
assert findKey(10) == 'Not Found'

My friend says that I should also put equivalent Java code to lighten up readers’ minds :-). So here goes …

HashMap<String, List<Integer>> mapOfListValues = new HashMap<String,List<Integer>>() {
put("a", Arrays.asList(1,2));
put("b", Arrays.asList(3,4));
put("c", Arrays.asList(5,6));
put("d", Arrays.asList(7,8));

public String findKey(...) {
blah blah, iterator, find, check if rest of world is not null,  catch exceptions and then a lot of code goes here

Yawn… you get the point..


One Response to Groovy #4 – A list of map of lists OLC

  1. asoftwareguy says:

    I thought it would be nice for people to see how succinct the Groovy syntax is compared to the java equivalent. Thanks for the mention 🙂


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: