Java SortedMap 接口

SortedMap接口是Java集合框架的一部分,提供对存储在Map中的键进行排序的功能。

它继承了Map接口

Java SortedMap interface extends the Map interface.


实现SortedMap的类

由于SortedMap是一个接口,我们无法直接创建它的对象。

为了使用SortedMap接口的功能,我们需要使用实现它的TreeMap类。

The Java TreeMap class implements the SortedMap interface.


如何使用SortedMap?

要使用SortedMap,我们必须先导入java.util.SortedMap包。导入包后,我们可以这样创建一个有序Map。

// SortedMap implementation by TreeMap class
SortedMap<Key, Value> numbers = new TreeMap<>();

我们使用TreeMap类创建了一个名为numbers的有序Map。

这里,

  • Key - 用于将 map 中的每个元素(值)关联起来的唯一标识符
  • Value - 由键在 map 中关联的元素

在这里,我们没有使用任何参数来创建有序Map。因此,Map将按照自然顺序(升序)排序。


SortedMap的方法

SortedMap接口包含了Map接口的所有方法。这是因为MapSortedMap的超接口。

除了所有这些方法之外,以下是SortedMap接口特有的方法。

  • comparator() - 返回一个可用于对Map中的键进行排序的比较器
  • firstKey() - 返回有序Map的第一个键
  • lastKey() - 返回有序Map的最后一个键
  • headMap(key) - 返回Map中所有键小于指定key的条目
  • tailMap(key) - 返回Map中所有键大于或等于指定key的条目
  • subMap(key1, key2) - 返回Map中键介于key1key2之间(包括key1)的所有条目

欲了解更多信息,请访问Java SortedMap(官方Java文档)


TreeMap类中SortedMap的实现

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

class Main {

    public static void main(String[] args) {
        // Creating SortedMap using TreeMap
        SortedMap<String, Integer> numbers = new TreeMap<>();

        // Insert elements to map
        numbers.put("Two", 2);
        numbers.put("One", 1);
        System.out.println("SortedMap: " + numbers);


        // Access the first key of the map
        System.out.println("First Key: " + numbers.firstKey());

        // Access the last key of the map
        System.out.println("Last Key: " + numbers.lastKey());

        // Remove elements from the map
        int value = numbers.remove("One");
        System.out.println("Removed Value: " + value);
    }
}

输出

SortedMap: {One=1, Two=2}
First Key: One
Last Key: Two
Removed Value: 1

在此,我们展示了SortedMap接口的工作原理。如果您想了解更多关于其实现的信息,请访问Java TreeMap

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战