java将一个map复制_Java程序将所有键值对从一个Map复制到另一个Map

若要复制,请使用putAll()方法。

让我们首先创建两个Map-

第一张映射-HashMap hm = new HashMap();

hm.put("Wallet", new Integer(700));

hm.put("Belt", new Integer(600));

第二张映射-HashMap hm2 = new HashMap();

hm.put("Bag", new Integer(1100));

hm.put("Sunglasses", new Integer(2000));

hm.put("Frames", new Integer(800));

现在,将键值对从一个Map复制到另一个Map-hm.putAll(hm2);

以下是将所有键值对从一个Map复制到另一个Map的示例-

示例import java.util.*;

public class Demo {

public static void main(String args[]) {

//创建哈希映射1-

HashMap hm = new HashMap();

hm.put("Wallet", new Integer(700));

hm.put("Belt", new Integer(600));

System.out.println("Map1 = "+hm);

//创建哈希映射2-

HashMap hm2 = new HashMap();

hm.put("Bag", new Integer(1100));

hm.put("Sunglasses", new Integer(2000));

hm.put("Frames", new Integer(800));

hm.putAll(hm2);

System.out.println("Map1 after copying values of Map2 = "+hm);

}

}

输出结果Map1 = {Belt=600, Wallet=700}

Map1 after copying values of Map2 = {Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000}

你可能感兴趣的:(java将一个map复制)