Java TreeMap Tutorial with Examples

Java TreeMap is a Red-Black tree based implementation of Java’s Map interface.

Java TreeMap是Java Map接口的基于红黑树的实现

The entries in a TreeMap are always sorted based on the natural ordering of the keys, or based on a custom Comparator that you can provide at the time of creation of the TreeMap.

TreeMap中的条目始终根据键的自然顺序或您在创建TreeMap时可以提供的自定义Comparator进行排序

The TreeMap class is part of Java’s collection framework. It implements the NavigableMap interface, which in turn extends the SortedMap interface. Following is the class hierarchy of TreeMap -

TreeMap类是Java集合框架的一部分。它实现了NavigableMap接口,该接口又扩展了SortedMap接口。以下是TreeMap的类层次结构

The SortedMap interface provides functionalities to maintain the ordering of keys. And the NavigableMap interface provides functionalities to navigate through the map. For example, finding the entry just greater than or just less than the given key, finding the first and last entry in the TreeMap etc.

例如,找到刚好大于或小于给定键的条目,找到TreeMap中的第一个和最后一个条目

Since a TreeMap implements NavigableMap interface, it has the functionalities of both the NavigableMap as well as the SortedMap.

由于TreeMap实现了NavigableMap接口,因此它既具有NavigableMap的功能,又具有SortedMap的功能

Following are few key points to note about TreeMap in Java -

以下是有关Java中TreeMap的几点注意事项

  • A TreeMap is always sorted based on keys. The sorting order follows the natural ordering of keys. You may also provide a custom Comparator to the TreeMap at the time of creation to let it sort the keys using the supplied Comparator.

    TreeMap始终基于键进行排序。排序顺序遵循键的自然顺序。您还可以在创建时向TreeMap提供自定义比较器,以使其使用提供的比较器对键进行排序

  • A TreeMap cannot contain duplicate keys.

    TreeMap不能包含重复的键

  • TreeMap cannot contain the null key. However, It can have null values.

    TreeMap不能包含null键。但是,它可以具有空值

  • TreeMap is not synchronized. Access to TreeMaps must be synchronized explicitly in a multi-threaded environment.

    TreeMap不同步。必须在多线程环境显示同步对TreeMap的访问

Creating a TreeMap

1. Simple TreeMap

This example shows how to create a simple TreeMap and add new key-value pairs to it. The entries in the TreeMap will be sorted based on the natural ordering of keys -

本示例说明如何创建一个简单的TreeMap并向其添加新的键值对。TreeMap中的条目将根据键的自然顺序进行排序-

package com.callicoder.treemap;

import java.util.SortedMap;
import java.util.TreeMap;

public class CreateTreeMapExample {

    public static void main(String[] args) {

        // Creating a TreeMap
        SortedMap<String, String> fileExtensions = new TreeMap<>();

        // Adding new key-value pairs to a TreeMap
        // 将新的键值对添加到TreeMap
        fileExtensions.put("python", ".py");
        fileExtensions.put("c++", ".cpp");
        fileExtensions.put("kotlin", ".kt");
        fileExtensions.put("golang", ".go");
        fileExtensions.put("java", ".java");

        // Printing the TreeMap (Output will be sorted based on keys)
        // 打印TreeMap(输出将根据键排序)
        System.out.println(fileExtensions);
    }
}

Output

{c++=.cpp, golang=.go, java=.java, kotlin=.kt, python=.py}

2. TreeMap with a custom Comparator (Descending Order)

带有自定义比较器的TreeMap(降序)

This example demonstrates how to create a TreeMap with a custom comparator that orders the TreeMap entries in the descending order of keys -

本示例演示如何使用自定义比较器创建TreeMap,该自定义比较器按键的降序对TreeMap条目进行排序

package com.callicoder.treemap;

import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;

public class CreateTreeMapCustomComparatorExample {

    public static void main(String[] args) {

        // Creating a TreeMap with a Custom comparator (Descending order)
        // 使用自定义比较器创建TreeMap(降序)
        SortedMap<String, String> fileExtensions = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.compareTo(o1);
            }
        });

        /*
            The above TreeMap with custom Comparator can be simply written as -
            上面带有自定义比较器的TreeMap可以简单地写为-
            SortedMap<String, String> fileExtensions = new TreeMap<>(Comparator.reverseOrder());
        */

        // Adding new key-value pairs to a TreeMap
        // 将新的键值对添加到TreeMap
        fileExtensions.put("python", ".py");
        fileExtensions.put("c++", ".cpp");
        fileExtensions.put("kotlin", ".kt");
        fileExtensions.put("golang", ".go");
        fileExtensions.put("java", ".java");

        // Printing the TreeMap (The keys will be sorted based on the supplied comparator)
        // 打印TreeMap(将根据提供的比较器对键进行排序)
        System.out.println(fileExtensions);
    }
}

Output

{python=.py, kotlin=.kt, java=.java, golang=.go, c++=.cpp}

3. TreeMap with a custom Comparator (Case Insensitive Order)

具有自定义比较器的TreeMap(不区分大小写的顺序)

The following example shows how to create a Case Insensitive Map by passing a custom CASE_INSENSITIVE_ORDER comparator to the TreeMap. The TreeMap will ignore case while ordering the keys.

以下示例说明如何通过将自定义CASE_INSENSITIVE_ORDER比较器传递给TreeMap来创建不区分大小写的映射。在订购键时,TreeMap将忽略大小写

package com.callicoder.treemap;

import java.util.SortedMap;
import java.util.TreeMap;

public class CreateTreeMapCaseInsensitiveOrderExample {

    public static void main(String[] args) {

        // TreeMap with keys sorted by ignoring case
        // 通过忽略大小写对键排序的TreeMap
        SortedMap<String, String> fileExtensions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

        /*
            The above statement is the short from of -
            SortedMap<String, String> fileExtensions = new TreeMap<>(new Comparator<String>() {
                @Override
                public int compare(String s1, String s2) {
                    return s1.compareToIngnoreCase(s2);
                }
            });
         */
        fileExtensions.put("PYTHON", ".py");
        fileExtensions.put("c++", ".cpp");
        fileExtensions.put("KOTLIN", ".kt");
        fileExtensions.put("Golang", ".go");

        // The keys will be sorted ignoring the case
        // (Try removing String.CASE_INSENSITIVE_ORDER and see the output)
        // 键将被忽略大小写排序(尝试删除String.CASE_INSENSITIVE_ORDER并查看输出)
        System.out.println(fileExtensions);
    }
}

Output

{c++=.cpp, Golang=.go, KOTLIN=.kt, PYTHON=.py}

Accessing the entries of a TreeMap

访问TreeMap的条目

The following example demonstrates how to -

  • Find the size of a TreeMap.

    查找TreeMap的大小

  • Check if a given key exists in a TreeMap.

    检查给定的键是否在TreeMap中存在

  • Retrieve the first entry in the TreeMap.

    检索TreeMap中的第一个条目

  • Retrieve the last entry in the TreeMap.

    检索TreeMap中的最后一个条目

  • Retrieve the entry whose key is just lower than the given key.

    检索键刚好低于给定键的条目

  • Retrieve the entry whose key is just higher than the given key.

  • 检索键刚好高于给定键的条目

package com.callicoder.treemap;

import java.util.Map;
import java.util.TreeMap;

public class AccessEntriesFromTreeMapExample {

    public static void main(String[] args) {
        TreeMap<Integer, String> employees = new TreeMap<>();

        employees.put(1003, "Rajeev");
        employees.put(1001, "Janes");
        employees.put(1002, "Sachin");
        employees.put(1004, "Chris");

        System.out.println("Employees map : " + employees);

        // Finding the size of a TreeMap
        // 查找TreeMap的大小
        System.out.println("Total number of employees : " + employees.size());

        // Check if a given key exists in a TreeMap
        // 检查TreeMap中是否存在给定键
        Integer id = 1004;
        if (employees.containsKey(id)) {
            // Get the value associated with a given key in a TreeMap
            // 获取与TreeMap中给定键关联的值
            String name = employees.get(id);
            System.out.println("Employee with id " + id + " : " + name);
        } else {
            System.out.println("Employee does not exist with id : " + id);
        }

        // Find the first and last entry
        // 查找第一个和最后一个条目
        System.out.println("First entry in employees map : " + employees.firstEntry());
        System.out.println("Last entry in employees map : " + employees.lastEntry());

        // Find the entry whose key is just less than the given key
        Map.Entry<Integer, String> employeeJustBelow = employees.lowerEntry(1002);
        System.out.println("Employee just below id 1002 : " + employeeJustBelow);

        // Find the entry whose key is just higher than the given key
        Map.Entry<Integer, String> employeeJustAbove = employees.higherEntry(1002);
        System.out.println("Employee just above id 1002 : " + employeeJustAbove);
    }
}

Output

Employees map : {1001=Janes, 1002=Sachin, 1003=Rajeev, 1004=Chris}
Total number of employees : 4
Employee with id 1004 : Chris
First entry in employees map : 1001=Janes
Last entry in employees map : 1004=Chris
Employee just below id 1002 : 1001=Janes
Employee just above id 1002 : 1003=Rajeev

Removing Entries from a TreeMap

从TreeMap中删除条目

The example below shows how to -

  • Remove a key from a TreeMap.

    从TreeMap中删除一个键

  • Remove a key from a TreeMap only if it is associated with a given value.

    仅当键与给定值关联时,才从TreeMap中删除键

  • Remove the first entry of the TreeMap.

    删除TreeMap的第一个条目

  • Remove the last entry of the TreeMap.

    删除TreeMap的最后一个条目

package com.callicoder.treemap;

import java.util.Map;
import java.util.TreeMap;

public class RemoveEntriesFromTreeMapExample {

    public static void main(String[] args) {
        TreeMap<String, String> countryISOCodeMapping = new TreeMap<>();

        countryISOCodeMapping.put("India", "IN");
        countryISOCodeMapping.put("United States of America", "US");
        countryISOCodeMapping.put("China", "CN");
        countryISOCodeMapping.put("United Kingdom", "UK");
        countryISOCodeMapping.put("Russia", "RU");
        countryISOCodeMapping.put("Japan", "JP");

        System.out.println("CountryISOCodeMapping : " + countryISOCodeMapping);

        // Remove the mapping for a given key
        // 删除给定键的映射
        String countryName = "Japan";
        String isoCode = countryISOCodeMapping.remove(countryName);
        if (isoCode != null) {
            System.out.println("Removed (" + countryName + " => " + isoCode + ") from the TreeMap. New TreeMap " + countryISOCodeMapping);
        } else {
            System.out.println(countryName + " does not exist, or it is mapped to a null value");
        }

        // Remove the mapping for the given key only if it is mapped to the given value
        countryName = "India";
        boolean isRemoved = countryISOCodeMapping.remove(countryName, "IA");
        System.out.println("Was the mapping removed for " + countryName + "? : " + isRemoved);

        // Remove the first entry from the TreeMap
        Map.Entry<String, String> firstEntry = countryISOCodeMapping.pollFirstEntry();
        System.out.println("Removed firstEntry : " + firstEntry + ", New TreeMap : " + countryISOCodeMapping);

        // Remove the last entry from the TreeMap
        Map.Entry<String, String> lastEntry = countryISOCodeMapping.pollLastEntry();
        System.out.println("Removed lastEntry : " + lastEntry + ", New TreeMap : " + countryISOCodeMapping);

    }
}

Output

CountryISOCodeMapping : {China=CN, India=IN, Japan=JP, Russia=RU, United Kingdom=UK, United States of America=US}
Removed (Japan => JP) from the TreeMap. New TreeMap {China=CN, India=IN, Russia=RU, United Kingdom=UK, United States of America=US}
Was the mapping removed for India? : false
Removed firstEntry : China=CN, New TreeMap : {India=IN, Russia=RU, United Kingdom=UK, United States of America=US}
Removed lastEntry : United States of America=US, New TreeMap : {India=IN, Russia=RU, United Kingdom=UK}

Conclusion

That’s all folks! In this article, you learned what is a TreeMap, how to create a TreeMap, how to use a custom Comparator to alter the sorting order of a TreeMap, how to find the entries from a TreeMap, and how to remove entries from a TreeMap.

在本文中,您学习了什么是TreeMap,如何创建TreeMap,如何使用自定义Comparator更改TreeMap的排序顺序,如何从TreeMap中找到条目以及如何从TreeMap中删除条目

Thanks for reading. Please ask any doubts in the comment section below.

原文地址:https://www.cnblogs.com/PrimerPlus/p/13225632.html