map
- computeIfAbsent方法
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
return v;
}
该方法用于获取指定的key,若返回的value值为空,则执行传入的Function,并将结果存入map中。
举一个应用场景:统计字符数
public class Main {
public static void main(String[] args) {
Map<String, AtomicInteger> map = new HashMap<>();
List<String> list = Arrays.asList("hello","python","hello","world","hello");
for(String tag: list){
getOrCreate(tag, map, AtomicInteger::new).getAndIncrement();
}
System.out.println(map);
}
public static <K,V> V getOrCreate(K key, Map<K,V> map, Supplier<V> factory){
return map.computeIfAbsent(key, k -> factory.get());
}
}
总结:java8引入了函数式编程,使代码编写更加简洁,但也越难理解。