Java SortedMap putAll()方法及示例

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)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程