具有多个键和值的Hashmap?

时间:2017-05-02 07:56:26

标签: java hashmap

我想创建一个如下所示的HashMap:

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

我有多个值的多个键。这是最好的方法吗?

2 个答案:

答案 0 :(得分:5)

您需要的是Map<String, List<String>>

示例:

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);

输出:

  

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

答案 1 :(得分:1)

您可以创建此结构:

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

尽管如果你知道使用内部列表创建对象的结构,它会更有效率。