【问题标题】:How to achieve a multi valued hashmap like HashMap<String,Hashmap<String,String>> in Java [closed]如何在 Java 中实现像 HashMap<String,Hashmap<String,String>> 这样的多值哈希图 [关闭]
【发布时间】:2020-06-20 06:55:59
【问题描述】:

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

我想实现以下目标:

关键值
Col--->苹果-->苹果
Col--->球--->球
Col1--->树--->树

所以地图看起来像,
钥匙。价值
Col-->[apple-->Apple],[ball-->Ball]
Col1-->[树--->树]

请帮忙!

【问题讨论】:

标签: java collections hashmap


【解决方案1】:

在现代 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 来保持顺序。

【讨论】:

    【解决方案2】:

    我看不出你会有重复的键...

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

    这个选项有什么问题 - 我的意思是除了这样的事实之外,这似乎是某种家庭作业或理论用例......

    【讨论】:

    • 您需要将"tree" 放入innerMap1 :)
    • 只是一个测试,如果有人会阅读这篇文章;-) 我会修复它,谢谢!
    猜你喜欢
    • 2016-06-11
    • 2018-06-19
    • 1970-01-01
    • 2013-05-08
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2012-05-26
    相关资源
    最近更新 更多