1

I want to create a HashMap that looks like this:

{LOCATION =[China,Sydney, New York,...], NAME = [Bob Smith, Martha Stewart, Amanda Holmes,....], ORGANIZATION = [Matrix Inc, Paragon Pharmaceuticals, Wills Corp.,...]}

I have more than 1 key with multiple values. Whats the best way to do this?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
serendipity
  • 852
  • 13
  • 32

3 Answers3

5

What you need is a Map<String, List<String>>

example:

Map<String, List<String>> myMap = new HashMap<>();

myMap.put("Location", Arrays.asList("a", "b", "c"));
myMap.put("Name", Arrays.asList("b", "mar", "ama"));
myMap.put("Org", Arrays.asList("ma", "par", "wil"));

System.out.println(myMap);

output:

{Org=[ma, par, wil], Location=[a, b, c], Name=[b, mar, ama]}

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

You can create this structure:

Map<String, List<String>> map = new HashMap<>();

Although, it'd be more efficient if you know the structure to create an object with the inner lists.

shmosel
  • 49,289
  • 6
  • 73
  • 138
Alex Roig
  • 1,534
  • 12
  • 18
  • it's interesting that despite being first, this answer didn't receive that many up-votes so far. I guess it's the "although" part, which basically claims "instead of using a hash-map, you can create a class to store the key + value pair" (the value being a list is actually irrelevant in that idea), and this would open a separate discussion. – danbanica May 02 '17 at 09:25
0

You can use a modified Hashmap that contains ArrayList's for keys and values. See my implementation: https://github.com/AdamDanischewski/Java-Playground/blob/main/KeyArrayHashMap.java

In the implementation above you can do things like search all or specific key indexes for a value and/or return all or a specific value index.

Also see this example just download and compile both with javac in the same directory. https://github.com/AdamDanischewski/Java-Playground/blob/main/KeyArrayHashMapExample.java

Run it like:

$>javac KeyArrayHashMap.java; javac KeyArrayHashMapExample.java; java KeyArrayHashMapExample 45
Searching all keys for all values: key 45, found value [first value for 45, second value for 45, third value for 45].
Searching 2nd key for all values: key 45, found value (*** key not found ***).
Searching 3rd keys for 1st value: key 45, found value (*** key not found ***).
Searching 1st val for all keys: key 45, found value [45, 145, 245].
Searching 2nd val for 3rd key: key 45, found value 245.
Adam D.
  • 159
  • 1
  • 5