Java教程

Java HashMap putAll()

Java HashMap putAll()

Java HashMap putAll() 方法将指定 Map 的所有键/值映射插入到 HashMap。
putAll() 方法的语法是:
hashmap.putAll(Map m)
这里, hashmapHashMap 类的对象。

putAll() 参数

putAll() 方法接受一个参数。
ma​​p-包含要插入到哈希映射中的映射的映射

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() 方法添加了从 primeNumbersnumbers 的所有映射。
请注意,键 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() 方法来添加从 treemaphashmap 的所有映射。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4