Java HashMap merge()

如果指定的键已与某个值关联,则该方法用指定函数的结果替换旧值。

merge() 方法的语法是

hashmap.merge(key, value, remappingFunction)

这里,hashmapHashMap 类的一个 对象


merge() 参数

merge() 方法接受 3 个参数

  • key - 要与指定 value 关联的键
  • value - 如果 key 已与任何值关联,则要与 key 关联的值
  • remappingFunction - 如果 key 已与某个值关联,则要与 key 关联的结果

merge()返回值

  • 返回与 key 关联的新值
  • 如果 key 没有关联值,则返回 null

注意:如果 remappingFunction 返回 null,则会删除指定 key 的映射。


示例 1:HashMap merge() 插入新条目

import java.util.HashMap;

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

    // insert entries to the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    int returnedValue = prices.merge("Shirt", 100, (oldValue, newValue) -> oldValue + newValue);
    System.out.println("Price of Shirt: " + returnedValue);

    // print updated HashMap
    System.out.println("Updated HashMap: " + prices);
  }
}

输出

HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shirt: 100
Updated HashMap: {Pant=150, Shirt=100, Bag=300, Shoes=200}

在上面的示例中,我们创建了一个名为 prices 的哈希表。请注意表达式:

prices.merge("Shirt", 100, (oldValue, newValue) -> oldValue + newValue)

在这里,我们已将 lambda 表达式 (oldValue, newValue) -> oldValue + newValue) 用作重映射函数。要了解有关 lambda 表达式的更多信息,请访问 Java Lambda Expressions

由于 prices 中不存在键 Shirt,因此 merge() 方法插入映射 Shirt=100。并且,重映射函数的结果被忽略。


示例 2:HashMap merge() 插入重复键的条目

import java.util.HashMap;

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

    // insert entries to the HashMap
    countries.put("Washington", "America");
    countries.put("Canberra", "Australia");
    countries.put("Madrid", "Spain");
    System.out.println("HashMap: " + countries);

    // merge mapping for key Washington
    String returnedValue = countries.merge("Washington", "USA", (oldValue, newValue) -> oldValue + "/" + newValue);
    System.out.println("Washington: " + returnedValue);

    // print updated HashMap
    System.out.println("Updated HashMap: " + countries);
  }
}

输出

HashMap: {Madrid=Spain, Canberra=Australia, Washington=America}
Washington: America/USA
Updated HashMap: {Madrid=Spain, Canberra=Australia, Washington=America/USA}, 

在上面的示例中,我们创建了一个名为 countries 的 hashmap。请注意表达式:

countries.merge("Washington", "USA", (oldValue, newValue) -> oldValue + "/" + newValue)

在这里,我们已将 lambda 表达式 (oldValue, newValue) -> oldValue + "/" + newValue) 用作重映射函数。

由于键 Washington 已存在于 countries 中,因此旧值被重映射函数返回的值替换。因此,Washington 的映射包含值 America/USA


示例 3:HashMap merge() 合并两个 HashMaps

import java.util.HashMap;

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

    // insert entries to the HashMap
    prices1.put("Pant", 230);
    prices1.put("Shoes", 350);
    System.out.println("HashMap 1: " + prices1);

    // create another hashmap
    HashMap<String, Integer> prices2 = new HashMap<>();

    //insert entries to the HashMap
    prices2.put("Shirt", 150);
    prices2.put("Shoes", 320);
    System.out.println("HashMap 2: " + prices2);

    // forEach() access each entries of prices2
    // merge() inserts each entry from prices2 to prices1
    prices2.forEach((key, value) -> prices1.merge(key, value, (oldValue, newValue) -> {
      
      // return the smaller value
      if (oldValue < newValue) {
        return oldValue;
      }
      else {
        return newValue;
      }
    }));

    System.out.println("Merged HashMap: " + prices1);
  }
}

输出

HashMap 1: {Pant=230, Shoes=350}
HashMap 2: {Shirt=150, Shoes=320}
Merged HashMap: {Pant=230, Shirt=150, Shoes=320}

在上面的示例中,我们创建了两个名为 prices1prices2 的 hashmaps。请注意代码:

    prices2.forEach((key, value) -> prices1.merge(key, value, (oldValue, newValue) -> {
      if (oldValue < newValue) {
        return oldValue;
      }
      else {
        return newValue;
      }
    }));

在这里,HashMap forEach() 方法访问 hashmap prices2 的每个条目,并将其合并到 hashmap prices1 中。我们使用了两个 lambda 表达式

  • (key, value) -> prices.merge(...) - 它访问 prices1 的每个条目并将其传递给 merge() 方法。
  • (oldValue, newValue) -> {...} - 这是一个重映射函数。它比较两个值并返回较小的值。

由于键 Shoes 存在于两个 hashmap 中,因此 Shoes 的值被重映射函数的结果替换。


Java HashMap merge() 与 putAll 对比

我们也可以使用 putAll() 方法合并两个 hashmaps。但是,如果一个键存在于两个 hashmaps 中,则旧值将被新值替换。

merge() 不同,putAll() 方法不提供重映射函数。因此,我们无法决定为重复键存储什么值。

要了解有关 putAll() 方法的更多信息,请访问 Java HashMap putAll()

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

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

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

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