Java Map putAll()方法及实例
该方法用于将指定地图中的所有映射复制到该地图中。
语法
void putAll(Map m)
参数: 该方法有唯一的参数map m,它包含要复制到给定地图的键值映射。
返回: 如果存在,该方法返回与键相关的前一个值,否则返回-1。
下面的程序显示了int putAll()方法的实现。
程序1:
// Java code to show the implementation of
// putAll method in Map interface
import java.util.*;
public class GfG {
// Driver code
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(3, "Three");
map.put(5, "Five");
map.put(7, "Seven");
map.put(9, "Nine");
System.out.println(map);
Map<Integer, String> mp = new HashMap<>();
mp.put(10, "Ten");
mp.put(30, "Thirty");
mp.put(50, "Fifty");
map.putAll(mp);
System.out.println(map);
}
}
输出:
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 50=Fifty, 3=Three, 5=Five, 7=Seven, 9=Nine, 10=Ten, 30=Thirty}
程序2: 下面的代码显示了put()的实现。
// Java code to show the implementation of
// putAll method in Map interface
import java.util.*;
public class GfG {
// Driver code
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map<String, String> map = new HashMap<>();
map.put("1", "One");
map.put("3", "Three");
map.put("5", "Five");
map.put("7", "Seven");
map.put("9", "Nine");
System.out.println(map);
Map<String, String> mp = new HashMap<>();
mp.put("10", "Ten");
mp.put("30", "Thirty");
mp.put("50", "Fifty");
map.putAll(mp);
System.out.println(map);
}
}
输出:
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine, 50=Fifty, 30=Thirty, 10=Ten}
参考资料:
Oracle文档