专栏名称: Java编程精选
关注语言编程Java,分享、交流Java编程技巧和信息
目录
相关文章推荐
51好读  ›  专栏  ›  Java编程精选

Map 只会 put、get?快来学这几个“新”方法

Java编程精选  · 公众号  · Java  · 2025-05-29 18:00

正文

请到「今天看啥」查看全文


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;
        }
        






请到「今天看啥」查看全文


推荐文章
酱子工厂  ·  最牛的小品笑翻赵本山!
8 年前
手机中国联盟  ·  智能手机平板流行,致中国近视率暴增
8 年前
中国安全生产网  ·  电焊作业要安全?这21条必须做到!
8 年前