Java HashMap replaceAll()

replaceAll() 方法的语法是

hashmap.replaceAll(Bifunction<K, V> function)

这里,hashmapHashMap 类的一个 对象


replaceAll() 参数

replaceAll() 方法接受一个参数。

  • function - 要应用于hashmap中每个条目的操作

replaceAll() 返回值

replaceAll() 方法不返回值。相反,它用function中的新值替换hashmap中的所有值。


示例 1:将所有值更改为大写

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // create an HashMap
        HashMap<Integer, String> languages = new HashMap<>();

        // add entries to the HashMap
        languages.put(1, "java");
        languages.put(2, "javascript");
        languages.put(3, "python");
        System.out.println("HashMap: " + languages);

        // Change all value to uppercase
        languages.replaceAll((key, value) -> value.toUpperCase());
        System.out.println("Updated HashMap: " + languages);
    }
}

输出

HashMap: {1=java, 2=javascript, 3=python}
Updated HashMap: {1=JAVA, 2=JAVASCRIPT, 3=PYTHON}

在上面的示例中,我们创建了一个名为 languages 的hashmap。请注意这一行:

languages.replaceAll((key, value) -> value.toUpperCase());

这里,

  • (key, value) -> value.toUpperCase() 是一个lambda表达式。它将hashmap的所有值转换为大写并返回。要了解更多信息,请访问 Java Lambda Expression
  • replaceAll() 用lambda表达式返回的值替换hashmap中的所有值。

示例 2:用键的平方替换所有值

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // create an HashMap
        HashMap<Integer, Integer> numbers = new HashMap<>();

        // insert entries to the HashMap
        numbers.put(5, 0);
        numbers.put(8, 1);
        numbers.put(9, 2);
        System.out.println("HashMap: " + numbers);

        // replace all value with the square of key
        numbers.replaceAll((key, value) -> key * key);;
        System.out.println("Updated HashMap: " + numbers);
    }
}

输出

HashMap: {5=0, 8=1, 9=2}
Updated HashMap: {5=25, 8=64, 9=81}

在上面的示例中,我们创建了一个名为 numbers 的哈希表。请注意这一行,

numbers.replaceAll((key, value) -> key * key);

这里,

  • (key, value) -> key * key - 计算 key 的平方并返回它
  • replaceAll() - 用 (key, value) -> key * key 返回的值替换hashmap中的所有值

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战