若要复制,请使用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}