Java SortedMap putAll()方法及示例

来源:这里教程网 时间:2026-02-17 21:11:25 作者:

Java SortedMap putAll()方法及示例

Java中SortedMap接口的 putAll() 方法用于将指定SortedMap中的所有映射复制到这个SortedMap中。

语法

void putAll(Map m)

参数: 该方法有唯一的参数 map m ,其中包含要复制到给定的SortedMap的键值映射。

返回: 如果存在,该方法返回与键相关的 前一个值 ,否则返回-1。

注意 :SortedMap中的putAll()方法是继承自Java中的Map接口。

以下程序说明了int putAll()方法的实现。

程序1 :

// Java code to show the implementation of// putAll method in SortedMap interface import java.util.*; public class GfG {     // Driver code    public static void main(String[] args)    {         // Initializing a SortedMap        SortedMap<Integer, String> map            = new TreeMap<>();         map.put(1, "One");        map.put(3, "Three");        map.put(5, "Five");        map.put(7, "Seven");        map.put(9, "Nine");        System.out.println(map);         SortedMap<Integer, String> mp            = new TreeMap<>();         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, 10=Ten, 30=Thirty, 50=Fifty}

程序2: 下面的代码显示了putAll()的实现。

// Java code to show the implementation of// putAll method in SortedMap interface import java.util.*;public class GfG {     // Driver code    public static void main(String[] args)    {         // Initializing a SortedMap        SortedMap<String, String> map            = new TreeMap<>();         map.put("1", "One");        map.put("3", "Three");        map.put("5", "Five");        map.put("7", "Seven");        map.put("9", "Nine");        System.out.println(map);         SortedMap<String, String> mp            = new TreeMap<>();         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, 10=Ten, 3=Three, 30=Thirty, 5=Five, 50=Fifty, 7=Seven, 9=Nine}

**参考资料: ** https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#put(K, %20V)

相关推荐