Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

Guavas MultiMap FTW

2016-04-21

I often have the need for some kind of “grouped list”. I have a key and a list of values. Usually I do the following:

HashMap<Integer, List<String>> map = new HashMap<>();
while (rs.next()) {
  if (!map.containsKey(rs.getInt(Env.KEY)))
        map.put(rs.getInt(ENV.KEY), new ArrayList<>());

  map.get(rs.getInt(Env.KEY)).add(rs.getString(Env.VALUE));
}

return map;

I saw an alternative some months ago but I could not remember the name of the class. Today @bernhard_joerg showed me Guavas Multimap. And what can I say, it was the missing class ;).

Multimap<Integer, String> multimap = ArrayListMultimap.create();
while (rs.next())
  multimap.put(rs.getInt(Env.KEY), rs.getString(Env.VALUE));    
return multimap.asMap();
  

Even if I don’t think the second approach speed up (or slow down) the method much, I like it because it’s somehow nicer to read.