📜  Java HashMap putAll()

📅  最后修改于: 2020-09-27 00:45:55             🧑  作者: Mango

Java HashMap putAll()方法将所有键/值映射从指定的Map插入到HashMap。

putAll()方法的语法为:

hashmap.putAll(Map m)

在这里, hashmapHashMap类的对象。


putAll()参数

putAll()方法采用单个参数。

  • 地图 -地图包含映射插入到散

putAll()返回值

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


示例1:Java HashMap putAll()
import java.util.HashMap;

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

    // create an HashMap
    HashMap 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 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映射到number

请注意,键2的值从22更改为2 。这是因为键2已经存在于数字中 。因此,该值将替换为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 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 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}

在上面的示例中,我们创建了TreeMapHashMap 。注意这一行,

hashmap.putAll(treemap);

在这里,我们使用了putAll()方法来添加从treemaphashmap的所有映射