【问题标题】:Java append `HashMap` values to existing HashMap if key matches如果键匹配,Java 将 `HashMap` 值附加到现有的 HashMap
【发布时间】:2020-04-06 19:14:27
【问题描述】:

我在下面打印了 HashMap(to.String())。

HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();

HashMap abc = {disabled={account={testConfiguration=1, iterate=1}}}

如果键 disabled 匹配,我想将 {group={iterate=1}} 附加到现有映射。

最后我的地图应该如下所示,我该如何实现呢?

HashMap abc = {disabled={account={testConfiguration=1, iterate=1}, {group={iterate=1}}}

【问题讨论】:

  • 能否详细说明一下。它不会冲走我现有的数据吗????
  • HashMap 中有哪些类型?
  • 添加到问题中
  • abc.get("disabled").put("group", newValue)?

标签: java data-structures collections hashmap


【解决方案1】:

我想你想要这个:

abc.computeIfPresent("disabled", (k,v) -> {
    v.put("group", yourValue);
    return v;
});

或者简单地说:

if (abc.containsKey("disabled")) {
    abc.get("disabled").put("group", yourValue);
}

我个人更喜欢第一种方法,因为它更快一些,并且可以与并发地图一起正常工作。

【讨论】:

    【解决方案2】:

    这是您所需输出的示例 disabled={account={testConfiguration=1, iterate=1}, group={iterate=1}}

    HashMap<String, Integer> accountmap = new HashMap<>();
        HashMap<String, Integer> groupMap = new HashMap<>();
        HashMap<String, HashMap<String, Integer>> disableMap = new HashMap<>();
        HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
        accountmap.put("testConfiguration",1);
        accountmap.put("iterate",1);
        disableMap.put("account",accountmap);
        abc.put("disabled", disableMap);
        if(abc.containsKey("disabled")){
            groupMap.put("iterate", 1);
            disableMap.put("group",groupMap);
        }
        System.out.println(abc.entrySet());
    

    【讨论】:

      【解决方案3】:

      以下代码为您提供以下格式的哈希图 {disabled={account={testConfiguration=1, iterate=1}, group={iterate=1}}}

      public static void main(String []args) {
          HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
      
          // HashMap abc = {disabled={account={testConfiguration=1, iterate=1}}}
          HashMap<String, Integer> thirdHash = new HashMap<>();
          thirdHash.put("testConfiguration", 1);
          thirdHash.put("iterate", 1);
      
          HashMap<String, HashMap<String, Integer>> secondHash = new HashMap<>();
          secondHash.put("account", thirdHash);
      
          abc.put("disabled", secondHash);
      
          // append {group={iterate=1}}
      
          HashMap<String, Integer> appendFirst = new HashMap();
          appendFirst.put("iterate", 1);
          if (abc.containsKey("disabled")) {
              abc.get("disabled").put("group", appendFirst);
          }
      
          System.out.println(abc);
      }
      

      快乐编码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 1970-01-01
        • 2013-06-20
        • 1970-01-01
        • 1970-01-01
        • 2019-01-13
        • 2016-02-14
        相关资源
        最近更新 更多