• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Java,合并两个Map

武飞扬头像
zzzb123456
帮助1

在Java中,合并两个Map可以使用putAll()方法,但是默认情况下,如果被合并的Map中有null值,它们会被丢弃。

如果想要保留null值,可以使用下面的代码:

  1.  
    public static <K, V> Map<K, V> mergeMaps(Map<K, V> map1, Map<K, V> map2) {
  2.  
    Map<K, V> result = new HashMap<>(map1);
  3.  
    for (Map.Entry<K, V> entry : map2.entrySet()) {
  4.  
    K key = entry.getKey();
  5.  
    V value = entry.getValue();
  6.  
    if (value != null) {
  7.  
    result.put(key, value);
  8.  
    } else if (!result.containsKey(key)) {
  9.  
    result.put(key, null);
  10.  
    }
  11.  
    }
  12.  
    return result;
  13.  
    }

这里将两个Map合并成一个新的Map,如果被合并的Map中的value有null,会被保留在新的Map中。

示例:

  1.  
    Map<String, String> map1 = new HashMap<>();
  2.  
    map1.put("a", "1");
  3.  
    map1.put("b", null);
  4.  
    map1.put("c", "3");
  5.  
     
  6.  
    Map<String, String> map2 = new HashMap<>();
  7.  
    map2.put("b", "2");
  8.  
    map2.put("c", null);
  9.  
    map2.put("d", "4");
  10.  
     
  11.  
    Map<String, String> result = mergeMaps(map1, map2);
  12.  
    System.out.println(result); // {a=1, b=null, c=null, d=4}

输出结果中,被合并的Map中的value为null的键值对被保留了下来。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggakha
系列文章
更多 icon
同类精品
更多 icon
继续加载