Map接口
Map<String, String> m = new HashMap<String, String>(); m.put("a", "A"); m.put("b", "B"); m.put("c", "C");
1.getOrDefault
返回Map中key对应的value值,value值为null时返回null。如果不存在此key值,则返回defaultValue值
/** * Returns the value to which the specified key is mapped, or * {@code defaultValue} if this map contains no mapping for the key.*/ default V getOrDefault(Object key, V defaultValue) { V v; return (((v = get(key)) != null) || containsKey(key)) ? v : defaultValue; }
测试:
System.out.println(m.getOrDefault("a", "A1")); //->A
System.out.println(m.getOrDefault("d", "D")); //->D
m.put("e", null);
System.out.println(m.getOrDefault("e", "E")); //->null
2.forEach
使用lambda表达式遍历Map集合
/** * Performs the given action for each entry in this map until all entries * have been processed or the action throws an exception.*/ default void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); for (Map.Entry<K, V> entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } action.accept(k, v); } }
测试:
m.forEach((k, v) -> { System.out.println("key:"+ k + "->value:"+ v); });
key:a->value:A
key:b->value:B
key:c->value:C
3.replaceAll
遍历整个集合,根据指定的表达式替换value的值
/** * Replaces each entry's value with the result of invoking the given * function on that entry until all entries have been processed or the * function throws an exception. */ default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Objects.requireNonNull(function); for (Map.Entry<K, V> entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } // ise thrown from function is not a cme. v = function.apply(k, v); try { entry.setValue(v); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } } }
测试:
m.replaceAll((k, v) -> { if(Objects.equals(v, "B")){ return "B haha"; } return v + " hehe"; });
key:a->value:A hehe
key:b->value:B haha
key:c->value:C hehe
4.putIfAbsent
根据指定的key查询集合。如果结果为null(此key的value为null或不存在此key)则将key,value添加到集合中。返回value值
如果结果不为null则不对集合作修改,返回get(key)
/** * If the specified key is not already associated with a value (or is mapped * to {@code null}) associates it with the given value and returns * {@code null}, else returns the current value. */ default V putIfAbsent(K key, V value) { V v = get(key); if (v == null) { v = put(key, value); } return v; }
测试:
m.putIfAbsent("a", "A");//未对集合作任何修改
m.putIfAbsent("a1", "A1");//添加元素成功
m.put("d", null);
m.putIfAbsent("d", "newd");//修改key:d的值成功
5.remove
从集合中remove指定的entry,根据传入的key和value去匹配。只有当都匹配时才可以remove成功返回true,否则返回false
/** * Removes the entry for the specified key only if it is currently * mapped to the specified value.*/ default boolean remove(Object key, Object value) { Object curValue = get(key); if (!Objects.equals(curValue, value) || (curValue == null && !containsKey(key))) { return false; } remove(key); return true; }
测试:
m.remove("a", "A1"); //移除失败
m.remove("a", "A"); //移除成功
key:b->value:B
key:c->value:C
6.replace(K key, V oldValue, V newValue)
更新指定的key的value值,只有当根据key和oldValue在集合中找到匹配的entry时才将对应的value更新为newValue。
更新成功时返回true,否则返回false
/** * Replaces the entry for the specified key only if currently * mapped to the specified value.*/ default boolean replace(K key, V oldValue, V newValue) { Object curValue = get(key); if (!Objects.equals(curValue, oldValue) || (curValue == null && !containsKey(key))) { return false; } put(key, newValue); return true; }
测试:
m.replace("a", "A", "newA");
key:a->value:newA
key:b->value:B
key:c->value:C
7.replace(K key, V value)
更新集合中指定key的值,如果有此key更新其value值为参数value,并返回旧的值。否则返回null
/** * Replaces the entry for the specified key only if it is * currently mapped to some value.*/ default V replace(K key, V value) { V curValue; if (((curValue = get(key)) != null) || containsKey(key)) { curValue = put(key, value); } return curValue; }
测试:
m.replace("a", "Anew1");
key:a->value:Anew1
key:b->value:B
key:c->value:C
8.computeIfAbsent
如果集合中指定key的value值为null或还没有此key,则根据传入的mappingFunction计算value值,最终将key和value值put进集合,返回计算后的value
当计算后的value值为null时不执行put方法,返回null
/** * If the specified key is not already associated with a value (or is mapped * to {@code null}), attempts to compute its value using the given mapping * function and enters it into this map unless {@code null}. */ 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; }
测试
m.computeIfAbsent("a1", k -> {return k+"computed";});
key:a1->value:a1computed
key:a->value:A
key:b->value:B
key:c->value:C
9.computeIfPresent(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)
如果集合中有此key并且指定key的value值不为null,则根据传入的mappingFunction计算value值,最终将key和value值put进集合,返回计算后的value
当计算后的value值为null时不执行put方法,返回null
/** * If the value for the specified key is present and non-null, attempts to * compute a new mapping given the key and its current mapped value. */ default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); V oldValue; if ((oldValue = get(key)) != null) { V newValue = remappingFunction.apply(key, oldValue); if (newValue != null) { put(key, newValue); return newValue; } else { remove(key); return null; } } else { return null; } }
测试:
m.computeIfPresent("a", (k, v) -> {return k+"^_^"+v;});
key:a->value:a^_^A
key:b->value:B
key:c->value:C
10.compute
根据指定的key及其value计算新的value值,如果计算后的value值不为null则更新原value值。如果为null则remove掉此entry。
如果没有此key,并且计算后的值不为null。则put进集合
更新成功之后返回新的值,否则返回null
/** * Attempts to compute a mapping for the specified key and its current * mapped value (or {@code null} if there is no current mapping). */ 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; } }
测试:
m.compute("a", (k, v) -> {return k+"^_^"+v;});
m.compute("d", (k, v) -> {return k+"^_^"+v;});
key:a->value:a^_^A
key:b->value:B
key:c->value:C
key:d->value:d^_^null
11.merge
根据key对应的value+传入的value值计算新的value值,如果计算后的值为null,则remove掉原key并返回null。
如果没有此key,并且计算后的值不为null。则put进集合
否则put到集合,最终返回计算后的值
/** * If the specified key is not already associated with a value or is * associated with null, associates it with the given non-null value. * Otherwise, replaces the associated value with the results of the given * remapping function, or removes if the result is {@code null}. This * method may be of use when combining multiple mapped values for a key. */ default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); Objects.requireNonNull(value); V oldValue = get(key); V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value); if(newValue == null) { remove(key); } else { put(key, newValue); } return newValue; }
测试:
m.merge("d", "D", String::concat);//原来没有这个key,put进去
m.merge("b", "大写的B", String::concat);//原来有此key,根据function计算后更新value值
m.merge("a", "大写的A", (oldValue, newValue) -> {return null;});//返回null,直接remove掉
key:b->value:B大写的B
key:c->value:C
key:d->value:D
浙公网安备 33010602011771号