正文
private static void
testForeach
() {
Map
map = new HashMap<>(4);
map.put(
"123"
,
"123"
);
// 老写法
for
(Map.Entry
entry : map.entrySet()) {
System.out.printf(
"老写法 key = %s, value = %s%n"
, entry.getKey(), entry.getValue());
}
// 新写法
map.forEach((key, value) -> System.out.printf(
"新写法 key = %s, value = %s%n"
, key, value));
}
merge
从名字可以想到,是合并entry使用的,但是具体是怎么合并呢?
看一下日常最常用的Map实现类HashMap对merge方法的实现
@Override
public V merge(K key, V value,
BiFunction super V, ? super V, ? extends V> remappingFunction) {
if (value == null || remappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node[] tab; Node first; int n, i;
int binCount = 0;
TreeNode t = null;
Node old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode)first).getTreeNode(hash, key);
else {
Node e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
}
if (old != null) {
V v;
if (old.value != null) {
int mc = modCount;
v = remappingFunction.apply(old.value, value);
if (mc != modCount) {
throw new ConcurrentModificationException();
}
} else {
v = value;
}