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 ツ
  • 45,713
  • 17
  • 64
  • 91
serendipity
  • 820
  • 13
  • 31

2 Answers2

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 ツ
  • 45,713
  • 17
  • 64
  • 91
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
  • 45,768
  • 6
  • 62
  • 130
Alex Roig
  • 1,394
  • 12
  • 15
  • 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