- V compute(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
- V computeIfAbsent(K key,Function<? super K,? extends V> mappingFunction)
- V computeIfPresent(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
- V merge(K key,V value,BiFunction<? super V,? super V,? extends V> remappingFunction)
- void forEach(BiConsumer<? super K,? super V> action)
写了个小例子,展示这几个函数的用法:
package halve;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.function.BiConsumer;
/**
* Created by fhqplzj on 16-7-18 at 上午9:24.
*/
public class Lotus {
public static void main(String[] args) {
String[] data = "a b c d a b c a b a".split(" ");
/**
* V computeIfAbsent(K key,Function<? super K,? extends V> mappingFunction)
*/
HashMap<String, LinkedList<String>> map1 = new HashMap<>();
for (String s : data) {
map1.computeIfAbsent(s, s1 -> new LinkedList<>()).add(s);
}
System.out.println("map1 = " + map1);
System.out.println();
/**
* V computeIfPresent(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
*/
for (String s : data) {
map1.computeIfPresent(s, (s1, strings) -> {
System.out.println("key=" + s1 + ",value=" + strings);
return strings;
});
}
System.out.println("map1 = " + map1);
System.out.println();
/**
* V compute(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
*/
for (String s : data) {
map1.compute(s, (s1, strings) -> {
System.out.println("key=" + s1 + ",size=" + strings.size() + ",value=" + strings);
return strings;
}).add("x");
}
System.out.println("map1 = " + map1);
System.out.println();
/**
* V merge(K key,V value,BiFunction<? super V,? super V,? extends V> remappingFunction)
*/
HashMap<String, String> map2 = new HashMap<>();
for (String s : data) {
map2.merge(s, s, String::concat);
}
System.out.println("map2 = " + map2);
System.out.println();
HashMap<String, Integer> map3 = new HashMap<>();
for (String s : data) {
map3.merge(s, 1, (x, y) -> x + y);
}
System.out.println("map3 = " + map3);
System.out.println();
/**
* void forEach(BiConsumer<? super K,? super V> action)
*/
BiConsumer<String, Integer> biConsumer = (s, integer) -> System.out.println(s + " occurs " + integer + " times!");
map3.forEach(biConsumer);
}
}