📜  从Java TreeMap 获取子图、头图和尾图

📅  最后修改于: 2022-05-13 01:55:32.262000             🧑  作者: Mango

从Java TreeMap 获取子图、头图和尾图

TreeMap 用于通过Java中的 AbstractMap 类实现 Map 接口和 Navigable Map。可以在 TreeMap 中使用各种构造函数来维护其键的排序顺序。

一、TreeMap的subMap()方法

Java中的 subMap() 方法用于返回由参数中指定范围的键定义的部分或部分映射。

句法:

newTreeMap = oldTreeMap.subMap(startKey,endKey)
  • startKey :地图的起点或下端,包括要考虑的点。
  • endKey :地图的端点或较高端,不包括要考虑的点。

退货类型:

Returns another map containing the portion of the map within the specified range.

执行:

Java
// Java code to illustrate submap() Method
  
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap tree
            = new TreeMap();
  
        // Mapping String to Integer
        tree.put(47, "Sashi");
        tree.put(82, "Ridhi");
        tree.put(66, "Himanshu");
        tree.put(98, "Sarthak");
        tree.put(87, "Sonika");
        tree.put(85, "Ritesh");
        tree.put(89, "Yogesh");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + tree);
  
        // printing the submap from key
        // 67(included) to 89(excluded)
        System.out.println("The subMap is: \n"
                           + tree.subMap(67, 89));
  
        // if start key and end key are same then
        // this method returns a null map
        System.out.println("Empty subMap: \n"
                           + tree.subMap(67, 67));
    }
}


Java
// Java code to illustrate headmap() method
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap tree
            = new TreeMap();
  
        // Mapping String to Integer
        tree.put(47, "Sashi");
        tree.put(82, "Ridhi");
        tree.put(66, "Himanshu");
        tree.put(98, "Sarthak");
        tree.put(87, "Sonika");
        tree.put(85, "Ritesh");
        tree.put(89, "Yogesh");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + tree);
  
        // this will print all the key-value
        // pairs which are less than 67
        System.out.println("The headMap is: \n"
                           + tree.headMap(67));
    }
}


Java
// Java code to illustrate tailmap() Method
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap tree
            = new TreeMap();
  
        // Mapping String to Integer
        tree.put(47, "Sashi");
        tree.put(82, "Ridhi");
        tree.put(66, "Himanshu");
        tree.put(98, "Sarthak");
        tree.put(87, "Sonika");
        tree.put(85, "Ritesh");
        tree.put(89, "Yogesh");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + tree);
  
        // this will print all the key-value pairs
        // which are greater than or equal to 67
        System.out.println("The tailMap is: \n"
                           + tree.tailMap(67));
    }
}


Java
// Combine operation on getting submap,
// headmap, and tailmap from Java TreeMap
  
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap originalTree
            = new TreeMap();
  
        // Mapping String to Integer
        originalTree.put(82, "Ridhi");
        originalTree.put(87, "Sonika");
        originalTree.put(85, "Ritesh");
        originalTree.put(89, "Yogesh");
        originalTree.put(80, "Yashdeep");
        originalTree.put(99, "Raushan");
        originalTree.put(67, "Shishya");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + originalTree);
  
        // submap from key 67(included) to 89(excluded)
        Map newSubMap
            = originalTree.subMap(67, 89);
  
        // doing some modification in map named
        // newSubMap and this modification is going to
        // be refelected in the original treemap also
        newSubMap.remove(67);
  
        // printing the original treemap to see the
        // modification
        System.out.println(
            "The original map after remove operation is: \n"
            + originalTree);
  
        // creating a new map named newHeadMap
        Map newHeadMap
            = originalTree.headMap(87);
  
        // doing some modification in map named
        // newHeadMap and this modification is going to
        // be refelected in the original treemap also
        newHeadMap.remove(82);
  
        // printing the original
        // treemap to see the modification
        System.out.println(
            "The original map after remove operation: \n"
            + originalTree);
  
        // creating a new map named newTailMap
        Map newTailMap
            = originalTree.tailMap(85);
  
        // doing some modification in map named
        // newHeadMap and this modification is going to
        // be refelected in the original treemap also
        newTailMap.put(94, "Ankit");
  
        // printing the original treemap
        // to see the modification
        System.out.println(
            "The original map after put operation is: \n"
            + originalTree);
    }
}


Java
// Exception when trying to put an entry in
// the map which is out of the range of the map
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap originalTree
            = new TreeMap();
  
        // Mapping String to Integer
        originalTree.put(47, "Sashi");
        originalTree.put(82, "Ridhi");
        originalTree.put(66, "Himanshu");
        originalTree.put(98, "Sarthak");
        originalTree.put(87, "Sonika");
        originalTree.put(85, "Ritesh");
        originalTree.put(89, "Yogesh");
        originalTree.put(80, "Yashdeep");
        originalTree.put(99, "Raushan");
        originalTree.put(67, "Shishya");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + originalTree);
  
        // submap from key 67(included) to 89(excluded)
        Map newSubMap
            = originalTree.subMap(67, 89);
  
        // This will throw an exception because
        // we can give key in between 67 - 89
        newSubMap.put(89, "Sandra");
  
        Map newHeadMap
            = originalTree.headMap(87);
  
        // This will throw an exception because
        // in newHeadMap we can only put key < 87
        newHeadMap.put(98, "Aman");
  
        Map newTailMap
            = originalTree.tailMap(87);
  
        // This will throw an exception because
        // in newTailMap we can only put key >= 87
        newTailMap.put(86, "Aman");
    }
}


Java
// submap, headmap, and tailmap from Java
// TreeMap on User-Defined class
import java.util.Map;
import java.util.TreeMap;
// user defined class
class friendsDetail {
  
    // class field
    private String name;
    private String nickName;
  
    // parameterised constructor
    public friendsDetail(String name, String nickName)
    {
        this.name = name;
        this.nickName = nickName;
    }
  
    // getter for name
    public String getName() { return name; }
  
    // setter for name
    public void setName(String name) { this.name = name; }
  
    // getter for nickname
    public String getnickName() { return nickName; }
  
    // setter for nickname
    public void setNickName(int id)
    {
        this.nickName = nickName;
    }
  
    // overriding toString method
    public String toString()
    {
        // return super.toString();
        return "(" + this.getName() + ":"
            + this.getnickName() + ")";
    }
}
public class GFG {
  
    public static void main(String[] args)
    {
        // Mapping user defined class to Integer
        TreeMap originalTree
            = new TreeMap<>();
        originalTree.put(2029, new friendsDetail(
                                   "Raushan", "Chamgader"));
        originalTree.put(
            2022, new friendsDetail("Yashdeep", "Dopa"));
        originalTree.put(
            2019, new friendsDetail("Shishya", "Gorilla"));
        originalTree.put(
            2021, new friendsDetail("Sonika", "Chipkali"));
        originalTree.put(
            2025, new friendsDetail("Himanshu", "Lalten"));
        originalTree.put(
            2023, new friendsDetail("Sarthak", "Nagin"));
        originalTree.put(
            2020, new friendsDetail("Tsering", "Battak"));
        originalTree.put(
            2018, new friendsDetail("Abhishek", "Liquid"));
  
        // printing our original class
        System.out.println("This is original treemap");
        for (Map.Entry map :
             originalTree.entrySet()) {
            System.out.println("Name: " + map.getKey()
                               + " \t Name & Nickname: "
                               + map.getValue());
        }
  
        // printing submap from 2020 to 2024
        System.out.println("\n\nThis is submap");
        Map subMap
            = originalTree.subMap(2020, 2024);
        for (Map.Entry map :
             subMap.entrySet()) {
            System.out.println("Name: " + map.getKey()
                               + " \t Name & Nickname: "
                               + map.getValue());
        }
  
        // printing headmap for keys < 2020
        System.out.println("\n\nThis is headmap");
        Map headMap
            = originalTree.headMap(2020);
        for (Map.Entry map :
             headMap.entrySet()) {
            System.out.println("Name: " + map.getKey()
                               + " \t Name & Nickname: "
                               + map.getValue());
        }
  
        // printing tailmap for keys >=2025
        System.out.println("\n\nThis is tailmap");
        Map tailMap
            = originalTree.tailMap(2025);
        for (Map.Entry map :
             tailMap.entrySet()) {
            System.out.println("Name: " + map.getKey()
                               + " \t Name & Nickname: "
                               + map.getValue());
        }
    }
}


输出
The original map is: 
{47=Sashi, 66=Himanshu, 82=Ridhi, 85=Ritesh, 87=Sonika, 89=Yogesh, 98=Sarthak}
The subMap is: 
{82=Ridhi, 85=Ritesh, 87=Sonika}
Empty subMap: 
{}

B. TreeMap 的 headMap() 方法

TreeMap 类的 headMap() 方法用于获取严格小于参数 key_value 的映射的所有对或部分。

句法:

newTreeMap = oldTreeMap.headMap(specifiedKey)

退货类型:

The method returns the portion of the map whose keys are less than the specified key.

执行:

Java

// Java code to illustrate headmap() method
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap tree
            = new TreeMap();
  
        // Mapping String to Integer
        tree.put(47, "Sashi");
        tree.put(82, "Ridhi");
        tree.put(66, "Himanshu");
        tree.put(98, "Sarthak");
        tree.put(87, "Sonika");
        tree.put(85, "Ritesh");
        tree.put(89, "Yogesh");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + tree);
  
        // this will print all the key-value
        // pairs which are less than 67
        System.out.println("The headMap is: \n"
                           + tree.headMap(67));
    }
}
输出
The original map is: 
{47=Sashi, 66=Himanshu, 82=Ridhi, 85=Ritesh, 87=Sonika, 89=Yogesh, 98=Sarthak}
The headMap is: 
{47=Sashi, 66=Himanshu}

C. TreeMap 的 tailMap() 方法

Java 中tailMap() Java用于获取key 大于等于参数中from_key 的map 的一部分或视图。

句法:

newMap = oldMap.tailMap(specifiedKey)

退货类型:

This method returns a map in which keys are greater than or equal to the specified key.

执行:

Java

// Java code to illustrate tailmap() Method
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap tree
            = new TreeMap();
  
        // Mapping String to Integer
        tree.put(47, "Sashi");
        tree.put(82, "Ridhi");
        tree.put(66, "Himanshu");
        tree.put(98, "Sarthak");
        tree.put(87, "Sonika");
        tree.put(85, "Ritesh");
        tree.put(89, "Yogesh");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + tree);
  
        // this will print all the key-value pairs
        // which are greater than or equal to 67
        System.out.println("The tailMap is: \n"
                           + tree.tailMap(67));
    }
}
输出
The original map is: 
{47=Sashi, 66=Himanshu, 82=Ridhi, 85=Ritesh, 87=Sonika, 89=Yogesh, 98=Sarthak}
The tailMap is: 
{82=Ridhi, 85=Ritesh, 87=Sonika, 89=Yogesh, 98=Sarthak}

重点:对 subMap()、headMap()、tailMap() 方法返回的地图所做的任何更改也将反映在原始地图中。

执行:

Java

// Combine operation on getting submap,
// headmap, and tailmap from Java TreeMap
  
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap originalTree
            = new TreeMap();
  
        // Mapping String to Integer
        originalTree.put(82, "Ridhi");
        originalTree.put(87, "Sonika");
        originalTree.put(85, "Ritesh");
        originalTree.put(89, "Yogesh");
        originalTree.put(80, "Yashdeep");
        originalTree.put(99, "Raushan");
        originalTree.put(67, "Shishya");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + originalTree);
  
        // submap from key 67(included) to 89(excluded)
        Map newSubMap
            = originalTree.subMap(67, 89);
  
        // doing some modification in map named
        // newSubMap and this modification is going to
        // be refelected in the original treemap also
        newSubMap.remove(67);
  
        // printing the original treemap to see the
        // modification
        System.out.println(
            "The original map after remove operation is: \n"
            + originalTree);
  
        // creating a new map named newHeadMap
        Map newHeadMap
            = originalTree.headMap(87);
  
        // doing some modification in map named
        // newHeadMap and this modification is going to
        // be refelected in the original treemap also
        newHeadMap.remove(82);
  
        // printing the original
        // treemap to see the modification
        System.out.println(
            "The original map after remove operation: \n"
            + originalTree);
  
        // creating a new map named newTailMap
        Map newTailMap
            = originalTree.tailMap(85);
  
        // doing some modification in map named
        // newHeadMap and this modification is going to
        // be refelected in the original treemap also
        newTailMap.put(94, "Ankit");
  
        // printing the original treemap
        // to see the modification
        System.out.println(
            "The original map after put operation is: \n"
            + originalTree);
    }
}
输出
The original map is: 
{67=Shishya, 80=Yashdeep, 82=Ridhi, 85=Ritesh, 87=Sonika, 89=Yogesh, 99=Raushan}
The original map after remove operation is: 
{80=Yashdeep, 82=Ridhi, 85=Ritesh, 87=Sonika, 89=Yogesh, 99=Raushan}
The original map after remove operation: 
{80=Yashdeep, 85=Ritesh, 87=Sonika, 89=Yogesh, 99=Raushan}
The original map after put operation is: 
{80=Yashdeep, 85=Ritesh, 87=Sonika, 89=Yogesh, 94=Ankit, 99=Raushan}

注意:如果尝试将超出这三个方法返回的地图范围的条目放入地图中,代码将抛出IllegalArgumentException

执行:

Java

// Exception when trying to put an entry in
// the map which is out of the range of the map
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        TreeMap originalTree
            = new TreeMap();
  
        // Mapping String to Integer
        originalTree.put(47, "Sashi");
        originalTree.put(82, "Ridhi");
        originalTree.put(66, "Himanshu");
        originalTree.put(98, "Sarthak");
        originalTree.put(87, "Sonika");
        originalTree.put(85, "Ritesh");
        originalTree.put(89, "Yogesh");
        originalTree.put(80, "Yashdeep");
        originalTree.put(99, "Raushan");
        originalTree.put(67, "Shishya");
  
        // printing the complete TreeMap
        System.out.println("The original map is: \n"
                           + originalTree);
  
        // submap from key 67(included) to 89(excluded)
        Map newSubMap
            = originalTree.subMap(67, 89);
  
        // This will throw an exception because
        // we can give key in between 67 - 89
        newSubMap.put(89, "Sandra");
  
        Map newHeadMap
            = originalTree.headMap(87);
  
        // This will throw an exception because
        // in newHeadMap we can only put key < 87
        newHeadMap.put(98, "Aman");
  
        Map newTailMap
            = originalTree.tailMap(87);
  
        // This will throw an exception because
        // in newTailMap we can only put key >= 87
        newTailMap.put(86, "Aman");
    }
}

输出:

Exception in thread "main" java.lang.IllegalArgumentException: key out of range
    at java.base/java.util.TreeMap$NavigableSubMap.put(TreeMap.java:1513)
    at GFG.main(File.java:29)

用户定义类的实现:

在这个例子中,不是使用包装类作为值,而是使用用户定义的类作为值,并将使用方法 subMap()、headMap() 和 tailMap()。这个例子只是为了更好地理解和更好地使用这三种方法。

执行:

Java

// submap, headmap, and tailmap from Java
// TreeMap on User-Defined class
import java.util.Map;
import java.util.TreeMap;
// user defined class
class friendsDetail {
  
    // class field
    private String name;
    private String nickName;
  
    // parameterised constructor
    public friendsDetail(String name, String nickName)
    {
        this.name = name;
        this.nickName = nickName;
    }
  
    // getter for name
    public String getName() { return name; }
  
    // setter for name
    public void setName(String name) { this.name = name; }
  
    // getter for nickname
    public String getnickName() { return nickName; }
  
    // setter for nickname
    public void setNickName(int id)
    {
        this.nickName = nickName;
    }
  
    // overriding toString method
    public String toString()
    {
        // return super.toString();
        return "(" + this.getName() + ":"
            + this.getnickName() + ")";
    }
}
public class GFG {
  
    public static void main(String[] args)
    {
        // Mapping user defined class to Integer
        TreeMap originalTree
            = new TreeMap<>();
        originalTree.put(2029, new friendsDetail(
                                   "Raushan", "Chamgader"));
        originalTree.put(
            2022, new friendsDetail("Yashdeep", "Dopa"));
        originalTree.put(
            2019, new friendsDetail("Shishya", "Gorilla"));
        originalTree.put(
            2021, new friendsDetail("Sonika", "Chipkali"));
        originalTree.put(
            2025, new friendsDetail("Himanshu", "Lalten"));
        originalTree.put(
            2023, new friendsDetail("Sarthak", "Nagin"));
        originalTree.put(
            2020, new friendsDetail("Tsering", "Battak"));
        originalTree.put(
            2018, new friendsDetail("Abhishek", "Liquid"));
  
        // printing our original class
        System.out.println("This is original treemap");
        for (Map.Entry map :
             originalTree.entrySet()) {
            System.out.println("Name: " + map.getKey()
                               + " \t Name & Nickname: "
                               + map.getValue());
        }
  
        // printing submap from 2020 to 2024
        System.out.println("\n\nThis is submap");
        Map subMap
            = originalTree.subMap(2020, 2024);
        for (Map.Entry map :
             subMap.entrySet()) {
            System.out.println("Name: " + map.getKey()
                               + " \t Name & Nickname: "
                               + map.getValue());
        }
  
        // printing headmap for keys < 2020
        System.out.println("\n\nThis is headmap");
        Map headMap
            = originalTree.headMap(2020);
        for (Map.Entry map :
             headMap.entrySet()) {
            System.out.println("Name: " + map.getKey()
                               + " \t Name & Nickname: "
                               + map.getValue());
        }
  
        // printing tailmap for keys >=2025
        System.out.println("\n\nThis is tailmap");
        Map tailMap
            = originalTree.tailMap(2025);
        for (Map.Entry map :
             tailMap.entrySet()) {
            System.out.println("Name: " + map.getKey()
                               + " \t Name & Nickname: "
                               + map.getValue());
        }
    }
}
输出
This is original treemap
Name: 2018      Name & Nickname: (Abhishek:Liquid)
Name: 2019      Name & Nickname: (Shishya:Gorilla)
Name: 2020      Name & Nickname: (Tsering:Battak)
Name: 2021      Name & Nickname: (Sonika:Chipkali)
Name: 2022      Name & Nickname: (Yashdeep:Dopa)
Name: 2023      Name & Nickname: (Sarthak:Nagin)
Name: 2025      Name & Nickname: (Himanshu:Lalten)
Name: 2029      Name & Nickname: (Raushan:Chamgader)


This is submap
Name: 2020      Name & Nickname: (Tsering:Battak)
Name: 2021      Name & Nickname: (Sonika:Chipkali)
Name: 2022      Name & Nickname: (Yashdeep:Dopa)
Name: 2023      Name & Nickname: (Sarthak:Nagin)


This is headmap
Name: 2018      Name & Nickname: (Abhishek:Liquid)
Name: 2019      Name & Nickname: (Shishya:Gorilla)


This is tailmap
Name: 2025      Name & Nickname: (Himanshu:Lalten)
Name: 2029      Name & Nickname: (Raushan:Chamgader)