一:简介
JDK1.8中Map新增了一些方法,其中一部分方法是为了简化代码的,如forEach,另外一些方法是为了防止null,使操作代码更加严谨。
二:Map
public interface Map<K,V> {
// 如果key存在,则忽略put操作
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
// 循环
public void forEach(BiConsumer<? super K, ? super V> action){...}
// 如果存在则计算:先判断key是否存在,如果key存在,将BiFunction计算的结果作为key的新值重新put进去
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {}
// 如果key不存在则将计算的结果put进去
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {}
// 只有key-value同时满足条件时才会删除
public boolean remove(Object key, Object value){}
// 如果key不存在,则返回默认值
public V getOrDefault(Object key, V defaultValue) {}
// 合并:将BiFunction的结果作为key的新值
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {}
三:示例
@Test
public void putIfAbsent() {
Map<String, String> map = new HashMap<>();
map.putIfAbsent("key", "oldValue");
// 如果key存在,则忽略put操作
map.putIfAbsent("key", "newValue");
String value = map.get("key");
System.out.println(value);
}
@Test
public void forEach() {
Map<String, String> map = new HashMap<>();
map.putIfAbsent("key1", "value1");
map.putIfAbsent("key2", "value1");
map.putIfAbsent("key3", "value1");
map.forEach((key, value) -> System.out.println(key + ":" + value));
}
@Test
public void computeIfPresent() {
Map<String, String> map = new HashMap<>();
map.putIfAbsent("key1", "value1");
// 如果存在则计算:先判断key是否存在,如果key存在,将BiFunction计算的结果作为key的新值重新put进去
map.computeIfPresent("key1", (key, value) -> key + "=" + value);
String value = map.get("key1");
System.out.println(value);
// 如果计算的结果为null,相当于从map中移除
map.computeIfPresent("key1", (k, v) -> null);
boolean contain = map.containsKey("key1");
System.out.println(contain);
}
@Test
public void computeIfAbsent() {
// 如果key不存在则将计算的结果put进去
Map<String, String> map = new HashMap<>();
map.computeIfAbsent("key2", v -> "value2");
boolean contain = map.containsKey("key2");
System.out.println(contain);
}
@Test
public void remove(){
Map<String, String> map = new HashMap<>();
map.putIfAbsent("key1", "value1");
boolean result = map.remove("key1", "value2");
System.out.println(result);
}
@Test
public void getOrDefault(){
Map<String, String> map = new HashMap<>();
String value = map.getOrDefault("key1", "default value");
System.out.println(value);
}
@Test
public void merge(){
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.merge("key1", "newValue", (value, newValue) -> value + "-" + newValue);
String value = map.get("key1");
// value1-newValue
System.out.println(value);
}