-2

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!

  • 1
    Does this answer your question? [HashMap: One Key, multiple Values](https://stackoverflow.com/questions/8229473/hashmap-one-key-multiple-values) – Eklavya Jun 20 '20 at 07:33

2 Answers2

0

I don't see that you would have duplicate keys...

HashMap<String, String> innerMap = new HashMap<>();
innerMap.put("apple", "Apple");
innerMap.put("ball", "Ball");
HashMap<String, String> innerMap1 = new HashMap<>();
innerMap1.put("tree", "Tree");
HashMap<String, HashMap<String, String>> outerMap = new HashMap<>();
outerMap.put("Col", innerMap);
outerMap.put("Col1", innerMap1);

What's wrong with this option - I mean apart from the fact like this seems to be some kind of homework or theoretical use case...

Oliver Gebert
  • 1,166
  • 1
  • 6
  • 20
0

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.

AminM
  • 822
  • 4
  • 11