05容器篇(D2_集合 - D5_企业容器常用 API)

目录

一、computeIfAbsent()

二、removeIfAbsent()


一、computeIfAbsent()

编程中经常遇到这种数据结构,判断一个map中是否存在这个key,如果存在则处理value的数据,

如果不存在,则创建一个满足value要求的数据结构放到value中。

以前常用的方法如下:

编程中经常遇到这种数据结构,判断一个map中是否存在这个key,如果存在则处理value的数据,

如果不存在,则创建一个满足value要求的数据结构放到value中。

以前常用的方法如下:

复制代码
public class TestComputeIfAbsent {
  static HashMap<String, Set<String>> hashMap = new HashMap<>();
  public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    set.add("zhangSan");
    hashMap.put("china", set);
    // 判断map中是否存在,如果存在则添加元素到set中,如果不存在则新建set添加到hashMap中
    if(hashMap.containsKey("china")) {
      hashMap.get("china").add("liSi");
    } else {
      Set<String> setTmp = new HashSet<>();
      setTmp.add("liSi");
      hashMap.put("china", setTmp);
    }
    System.out.println(hashMap.toString());
  }
}

官方非常的贴心,为了满足广大用户的要求,加入了computeIfAbsent() 这个api,

使用后以上代码变成了下面的形式:

复制代码
public class TestComputeIfAbsent {
  static HashMap<String, Set<String>> hashMap = new HashMap<>();
  public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    set.add("zhangSan");
    hashMap.put("china", set);
    // after JDK1.8
    hashMap.computeIfAbsent("china", key -> getValues(key)).add("liSi");
    System.out.println(hashMap.toString());
  }
 
  public static HashSet getValues(String key) {
    return new HashSet();
  }
}

hashMap.computeIfAbsent("china", key -> getValues(key)).add("liSi");的意思表示key为"China"的建值对

是否存在,返回的是value的值。

如果存在则获取china的值,并操作值的set添加数据"lisi"。

如果不存在,则调用方法,新创建set结构,将"lisi"添加到set中,再存入到hashMap中。

二、removeIfAbsent()

相关推荐
Aaron - Wistron10 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy123931021611 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
05664612 小时前
Python康复训练——常用标准库
开发语言·python·学习
极光代码工作室12 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
骊城英雄12 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#
吾儿良辰12 小时前
一个被BCL遗忘的高性能集合:C# CircularBuffer<T>深度解析
开发语言·windows·c#
昆曲之源_娄江河畔12 小时前
Python如何安装flask, pymssql
开发语言·python·flask·pymssql
Leighteen12 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
05664612 小时前
Python康复训练——控制流与函数
开发语言·python·学习
峥无13 小时前
C++11 深度详解:现代 C++ 基石全梳理
开发语言·c++·笔记