Java TreeMap subMap()方法及示例

Java TreeMap subMap()方法及示例

在Java中,TreeMap类的subMap()方法用于返回参数中指定的键值范围所定义的Map的一部分或几部分。在一个或另一个Map上的任何变化都会反映在另一个Map上。

语法

Tree_Map.subMap( _K startKey, K endKey_ )

参数: 该方法需要两个关键类型的参数。

  • 包括要考虑的点的起点或Map的下端。(startKey)
  • 端点或Map的高端,不包括要考虑的点。

返回类型: 该方法返回包含指定范围内的部分Map的另一张Map。

异常: 该方法会抛出三种类型的异常。

  • ClassCastException: 如果方法中提到的参数不能与这个Map的键进行比较,就会抛出这种异常。
  • NullPointerException: 如果其中一个参数是空值,而Map不接受任何空值,就会抛出这个异常。
  • IllegalArgumentException: 如果提到的参数超出了范围或者低端大于高端,就会抛出这个异常。

注意: 如果startKey等于endKey,那么将返回一个Null Map。

例子1 :

// Java Program to illustrate the subMap() method
// of TreeMap class
  
// Importing required classes
import java.util.*;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating an empty TreeMap by
        // declaring object of integer, string pairs
        TreeMap<Integer, String> tree_map
            = new TreeMap<Integer, String>();
  
        // Mapping string values to int keys
        // using put() method
        tree_map.put(10, "Geeks");
        tree_map.put(15, "4");
        tree_map.put(20, "Geeks");
        tree_map.put(25, "Welcomes");
        tree_map.put(30, "You");
  
        // Printing the elements of TreeMap
        System.out.println("The original map is: "
                           + tree_map);
  
        // Displaying the submap
        // using subMap() method
        System.out.println("The subMap is "
                           + tree_map.subMap(15, 30));
    }
}

输出

The original map is: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The subMap is {15=4, 20=Geeks, 25=Welcomes}

例2 :

// Java Program to Illustrate the subMap() method
  
// Importing required classes
import java.util.*;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty TreeMap by
        // declaring object of string, integer pairs
        TreeMap<String, Integer> tree_map
            = new TreeMap<String, Integer>();
  
        // Mapping int values to string keys
        // using put() method
        tree_map.put("Geeks", 10);
        tree_map.put("4", 15);
        tree_map.put("Geeks", 20);
        tree_map.put("Welcomes", 25);
        tree_map.put("You", 30);
  
        // Printing the elements of TreeMap
        System.out.println("The original map is: "
                           + tree_map);
  
        // Displaying the subMap
        // using subMap() method
        System.out.println(
            "The subMap is "
            + tree_map.subMap("Geeks", "Geeks"));
    }
}

输出

The original map is: {4=15, Geeks=20, Welcomes=25, You=30}
The subMap is {}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程