Java HashMap replaceAll()方法

java.util.HashMap.replaceAll(BiFunction<K, V> function) 方法用在该条目上调用给定函数的结果替换每个条目的值,直到处理完所有条目或该函数引发异常为止。

1 语法

void replaceAll(BiFunction<K, V> function)

2 参数

function:对每个条目的值进行运算的函数。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.HashMap.replaceAll(BiFunction<K, V> function)方法的例子
 */
import java.util.*;

public class Demo {
    public static void main(String args[]) {

        // create a HashMap having some entries
        HashMap<String, Integer>
                map1 = new HashMap<>();
        map1.put("key1", 1);
        map1.put("key2", 2);
        map1.put("key3", 3);
        map1.put("key4", 4);

        // print map details
        System.out.println("HashMap1: "
                + map1.toString());

        // replace oldValue with square of oldValue
        // using replaceAll method
        map1.replaceAll((key, oldValue)
                -> oldValue * oldValue);

        // print new mapping
        System.out.println("New HashMap: "
                + map1);
    }
}

输出结果为:

HashMap1: {key1=1, key2=2, key3=3, key4=4}
New HashMap: {key1=1, key2=4, key3=9, key4=16}

热门文章

优秀文章