跳到主要内容

Java HashMap replaceAll() 方法

replaceAll() 方法的语法是:

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

这里,hashmapHashMap 类的一个对象。

replaceAll() 方法的参数

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

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

replaceAll() 方法的返回值

replaceAll() 方法不返回任何值。它将 hashmap 的所有值替换为 function 返回的新值。

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

import java.util.HashMap;

class Main {
public static void main(String[] args) {
// 创建一个 HashMap
HashMap<Integer, String> languages = new HashMap<>();

// 向 HashMap 添加条目
languages.put(1, "java");
languages.put(2, "javascript");
languages.put(3, "python");
System.out.println("HashMap: " + languages);

// 将所有值更改为大写
languages.replaceAll((key, value) -> value.toUpperCase());
System.out.println("更新后的 HashMap: " + languages);
}
}

输出

HashMap: {1=java, 2=javascript, 3=python}
更新后的 HashMap: {1=JAVA, 2=JAVASCRIPT, 3=PYTHON}

在上述示例中,我们创建了一个名为 languages 的 hashmap。注意这行代码,

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

这里,

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

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

import java.util.HashMap;

class Main {
public static void main(String[] args) {
// 创建一个 HashMap
HashMap<Integer, Integer> numbers = new HashMap<>();

// 向 HashMap 插入条目
numbers.put(5, 0);
numbers.put(8, 1);
numbers.put(9, 2);
System.out.println("HashMap: " + numbers);

// 将所有值替换为键的平方
numbers.replaceAll((key, value) -> key * key);
System.out.println("更新后的 HashMap: " + numbers);
}
}

输出

HashMap: {5=0, 8=1, 9=2}
更新后的 HashMap: {5=25, 8=64, 9=81}

在上述示例中,我们创建了一个名为 numbers 的 hashmap。注意这行代码,

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

这里,

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