首页 > 解决方案 > 如何实现像HashMap这样的多值hashmap> 在 Java 中

问题描述

我希望外部映射具有重复键,因此不能使用传统的哈希映射。

我想实现以下目标:

键值
Col--->apple-->Apple
Col--->ball--->Ball
Col1--->tree--->Tree

所以地图看起来像,
关键。值
Col-->[apple-->Apple],[ball-->Ball]
Col1-->[tree--->Tree]

请帮忙!

标签: javacollectionshashmap

解决方案


在现代 Java 中执行此操作的一个很好、紧凑的方法是:

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

有点冗长,但我假设你实际上会在这个例子中这样做:

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

注意:我使用 LinkedHashMap 来保持顺序。


推荐阅读