Java HashMap putAll()

putAll() 方法的语法是

hashmap.putAll(Map m)

在这里,hashmapHashMap 类的一个对象


putAll() 参数

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

  • map - 包含要插入到哈希表中的映射的映射

putAll() 返回值

putAll() 方法不返回任何值。


示例 1:Java HashMap putAll()

import java.util.HashMap;

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

    // create an HashMap
    HashMap<String, Integer> primeNumbers = new HashMap<>();

    // add mappings to HashMap
    primeNumbers.put("Two", 2);
    primeNumbers.put("Three", 3);
    System.out.println("Prime Numbers: " + primeNumbers);

    // create another HashMap
    HashMap<String, Integer> numbers = new HashMap<>();
    numbers.put("One", 1);
    numbers.put("Two", 22);

    // Add all mappings from primeNumbers to numbers
    numbers.putAll(primeNumbers);
    System.out.println("Numbers: " + numbers);
  }
}

输出

Prime Numbers: {Two=2, Three=3}
Numbers: {One=1, Two=2, Three=3}

在上面的示例中,我们创建了两个名为 primeNumbersnumbers 的哈希表。注意这行代码:

numbers.putAll(primeNumbers);

在这里,putAll() 方法将 primeNumbers 中的所有映射添加到 numbers 中。

请注意,键 Two 的值从 22 更改为 2。这是因为键 Two 已经存在于 numbers 中。因此,该值将被 primeNumbers 中的新值替换。

注意:我们使用了 put() 方法向哈希表添加单个映射。要了解更多信息,请访问 Java HashMap put()


示例 2:将 TreeMap 中的映射插入 HashMap

import java.util.HashMap;
import java.util.TreeMap;

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

    // create a TreeMap of String type
    TreeMap<String, String> treemap = new TreeMap<>();

    // add mappings to the TreeMap
    treemap.put("A", "Apple");
    treemap.put("B", "Ball");
    treemap.put("C", "Cat");
    System.out.println("TreeMap: " + treemap);

    // create a HashMap
    HashMap<String, String> hashmap = new HashMap<>();

    // add mapping to HashMap
    hashmap.put("Y", "Yak");
    hashmap.put("Z", "Zebra");
    System.out.println("Initial HashMap: " + hashmap);

    // add all mappings from TreeMap to HashMap
    hashmap.putAll(treemap);
    System.out.println("Updated HashMap: " + hashmap);
  }
}

输出

TreeMap: {A=Apple, B=Ball, C=Cat}
Initial HashMap: {Y=Yak, Z=Zebra}
Updated HashMap: {A=Apple, B=Ball, C=Cat, Y=Yak, Z=Zebra}

在上面的示例中,我们创建了一个 TreeMap 和一个 HashMap。注意这行代码:

hashmap.putAll(treemap);

在这里,我们使用 putAll() 方法将 treemap 中的所有映射添加到 hashmap 中。

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

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

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

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