Java 中使用 computeIfAbsent 和 putIfAbsent 添加元素到 Map
在 Java 中,可以使用 computeIfAbsent 和 putIfAbsent 方法向 Map 添加元素。
使用 computeIfAbsent 添加元素
Map<String, List<Integer>> empCodeKeyAndLineValueMap = new HashMap<>();
String empCode = "emp123";
int lineNum = 10;
empCodeKeyAndLineValueMap.computeIfAbsent(empCode, k -> new ArrayList<>()).add(lineNum);
使用 putIfAbsent 添加元素
Map<String, List<Integer>> empCodeKeyAndLineValueMap = new HashMap<>();
String empCode = "emp123";
int lineNum = 10;
empCodeKeyAndLineValueMap.putIfAbsent(empCode, new ArrayList<>()).add(lineNum);
两种方法的比较
computeIfAbsent方法更简洁,它在添加元素的同时也创建了新的ArrayList对象,如果键已经存在则不会创建新的对象。putIfAbsent方法需要先判断键是否存在,如果不存在则创建新的ArrayList对象,然后添加元素。
选择方法的建议
- 如果需要在添加元素的同时创建新的对象,则建议使用
computeIfAbsent方法。 - 如果需要先判断键是否存在,再添加元素,则建议使用
putIfAbsent方法。
原文地址: https://www.cveoy.top/t/topic/qfAF 著作权归作者所有。请勿转载和采集!