Search code examples
javacollectionshashmap

How to achieve a multi valued hashmap like HashMap<String,Hashmap<String,String>> in Java


I want an outer map to have duplicate keys, therefore cannot use a traditional hashmap.

I want to achieve something like below:

Key Value
Col--->apple-->Apple
Col--->ball--->Ball
Col1--->tree--->Tree

so map would look like,
Key. Value
Col-->[apple-->Apple],[ball-->Ball]
Col1-->[tree--->Tree]

Please help!


Solution

  • A nice, compact way to do this in modern Java is:

    Map<String, Map<String, String>> map = new HashMap<>();
    map.computeIfAbsent("Col", k -> new HashMap<String,String>()).put("apple", "Apple");
    map.computeIfAbsent("Col", k -> new HashMap<String,String>()).put("ball", "Ball");
    map.computeIfAbsent("Col", k -> new HashMap<String,String>()).put("tree", "Tree");
    

    A little verbose but I'd assume you'd actually do this in a like in this example:

    String[][] values = {
      {"Col", "apple", "Apple"},
      {"Col", "ball", "Ball"},
      {"Col1", "tree", "Tree"},      
    };
    
    Map<String, Map<String, String>> map = new LinkedHashMap<>(); 
    for (String[] row : values) {
      map.computeIfAbsent(row[0], k -> new LinkedHashMap<String, String>()).put(row[1], row[2]);
    }
    

    Note: I used LinkedHashMap to preserve order.