The problem
Handling maps that store collection of items under each key is very common. The thing I have in mind is this:
Map<String, List<Integer>> playerScoresMap = new HashMap<String, List<Integer>>();
Let’s assume that it stores scores for players. The player name is the key, and the value is a list of points scored by the player in following rounds. The task is to add a new score for the player after the round.
Plain Java solution
The HashMap solution requires you to:
- check if the player key already exist in map
- if it does not exist – add the key and create new array with score
- if it exists, get its current score array
- add new score to the array
- store the array under the user key
Source code for it is:
private static void addToOldStyleMultimap(String playerName, int scoreToAdd) { List<Integer> scoresList = new ArrayList<Integer>(); if(playerScoresMap.containsKey(playerName)){ scoresList = playerScoresMap.get(playerName); } scoresList.add(scoreToAdd); playerScoresMap.put(playerName, scoresList); }
Guava solution
Guava has dedicated type for maps of that kind. Java’s:
Map<String, List<Integer>> playerScoresMap = new HashMap<String, List<Integer>>();
is equal to Guava’s Multimap:
Multimap<String, Integer> playerScoresMultimap = HashMultimap.create();
The difference is noticable in adding scores use case. To add new score for the player just make a call:
private static void addToGuavaMultimap(String playerName, Integer scoreToAdd) { playerScoresMultimap.put(playerName, scoreToAdd); }
Guava’s Multimap does all checks for you. If player key exists, it adds new score to its score array. If it does not exist, a new key with one element score array is added.
Guava Example
Calling addToGuavaMultimap in the following manner:
addToGuavaMultimap("Alan", 2); addToGuavaMultimap("Alan", 4); addToGuavaMultimap("Alan", 6); addToGuavaMultimap("Paul", 87); System.out.println("Guava multimap result: " + playerScoresMultimap);
results with output:
Guava multimap result: {Alan=[4, 2, 6], Paul=[87]}
Source code download
The source code for this post is on my github: https://github.com/yacekmm/looksok/tree/GuavaCacheDemo