computeIfAbsent
jdk源码
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;
}
用法1(value是数组)
private final static Map<String, Collection<String>> listValueMap = new HashMap<>();
private static void addValue(final String key, final String val) {
listValueMap.computeIfAbsent(key, k -> new LinkedHashSet<>()).add(val);
}
String key = "user";
addValue(key,"user1");
addValue(key,"user1");
addValue(key,"user2");
用户2:统计单词数
private final static Map<String, AtomicInteger> wordCountMap = new HashMap<>();
String[] keys = {"one","two","three","three","two","three"};
for(String str : keys) {
wordCountMap.computeIfAbsent(str,k-> new AtomicInteger(0)).incrementAndGet();
}
for(Map.Entry<String,AtomicInteger> kv : wordCountMap.entrySet()) {
System.out.println("key="+kv.getKey()+", value="+kv.getValue().get());
}
compute
jdk源码
default V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
// delete mapping
if (oldValue != null || containsKey(key)) {
// something to remove
remove(key);
return null;
} else {
// nothing to do. Leave things as they were.
return null;
}
} else {
// add or replace old mapping
put(key, newValue);
return newValue;
}
}
例子
private final static Map<String, Integer> wordCountIntegerMap = new HashMap<>();
String[] keys = {"one","two","three","three","two","three"};
for(String str : keys) {
wordCountIntegerMap.compute(str,(k,v)->{
Integer temp;
if(v==null){
temp = 0;
}else {
temp = v;
}
return ++temp;
});
}
computeIfPresentMap
jdk源码
default V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue;
if ((oldValue = get(key)) != null) { // 存在key && oldValue!=null
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) { // 新值!=null,则替换新值
put(key, newValue);
return newValue;
} else { // 新值==null ,则该key从map中删除
remove(key);
return null;
}
} else {
return null;
}
}
例子
private final static Map<String, Integer> computeIfPresentMap = new HashMap<>();
// 先放入map
computeIfPresentMap.put("three",1);
for(String str : keys) {
computeIfPresentMap.computeIfPresent(str,(k,v)-> v+1);
}
for(Map.Entry<String,Integer> kv : computeIfPresentMap.entrySet()) {
System.out.println("key="+kv.getKey()+", value="+kv.getValue());
}