有关HashMap的computeIfAbsent优雅使用方式

简介: 有关HashMap的computeIfAbsent优雅使用方式
使用hashMap对数据操作。
public class Test {
  static HashMap<String, Set<String>> hashMap = new HashMap<>();
  public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    set.add("北京");
    hashMap.put("city", set);
    // 判断map中是否存在,如果存在则添加元素到set中,如果不存在则新建set添加到hashMap中
    if(hashMap.containsKey("city")) {
      hashMap.get("city").add("苏州");
    } else {
      Set<String> set = new HashSet<>();
      setTmp.add("上海");
      hashMap.put("city", set);
    }
    System.out.println(hashMap.toString());
  }
}
优化之后的写法:
public class TestComputeIfAbsent {
  static HashMap<String, Set<String>> hashMap = new HashMap<>();
  public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    set.add("北京");
    hashMap.put("city", set);
  //以下写法是1.8以及之后的版本
    hashMap.computeIfAbsent("city", key -> getValues(key)).add("苏州");
    System.out.println(hashMap.toString());
  }
 
  public static HashSet getValues(String key) {
    return new HashSet();
  }
}
相关文章
|
5月前
有关HashMap的computeIfAbsent优雅使用方式
有关HashMap的computeIfAbsent优雅使用方式
65 0
|
Java
从源码学习Java的HashMap中的computeIfAbsent/computeIfPresent方法
从源码学习Java的HashMap中的computeIfAbsent/computeIfPresent方法
130 0
有关HashMap的computeIfAbsent优雅使用方式
有关HashMap的computeIfAbsent优雅使用方式
121 0
|
5月前
|
存储 算法 Java
【深入挖掘Java技术】「源码原理体系」盲点问题解析之HashMap工作原理全揭秘(下)
在阅读了上篇文章《【深入挖掘Java技术】「源码原理体系」盲点问题解析之HashMap工作原理全揭秘(上)》之后,相信您对HashMap的基本原理和基础结构已经有了初步的认识。接下来,我们将进一步深入探索HashMap的源码,揭示其深层次的技术细节。通过这次解析,您将更深入地理解HashMap的工作原理,掌握其核心实现。
54 0
【深入挖掘Java技术】「源码原理体系」盲点问题解析之HashMap工作原理全揭秘(下)
|
5月前
|
存储 安全 Java
从源码角度来谈谈 HashMap
HashMap的知识点可以说在面试中经常被问到,是Java中比较常见的一种数据结构。所以这一篇就通过源码来深入理解下HashMap。
75 0
从源码角度来谈谈 HashMap
|
5月前
|
存储 安全 Java
HashMap源码全面解析
HashMap源码全面解析
|
5月前
|
Java
IDEA debug HashMap源码的心得
IDEA debug HashMap源码的心得
47 0
|
4月前
|
存储 安全 Java
《ArrayList & HashMap 源码类基础面试题》面试官们最喜欢问的ArrayList & HashMap源码类初级问,你都会了?
《ArrayList & HashMap 源码类基础面试题》面试官们最喜欢问的ArrayList & HashMap源码类初级问,你都会了?
32 0
|
4月前
HashMap源码
HashMap源码
|
5月前
|
Java 索引
【JAVA学习之路 | 进阶篇】HashMap源码剖析
【JAVA学习之路 | 进阶篇】HashMap源码剖析