Guava Multimap demo

16 08 2015

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:

  1. check if the player key already exist in map
    1. if it does not exist – add the key and create new array with score
    2. if it exists, get its current score array
  2. add new score to the array
  3. 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>();
        scoresList = playerScoresMap.get(playerName);

    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:




Give Your feedback:

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

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

Google photo

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

%d bloggers like this: