SortedMap
接口是Java集合框架的一部分,提供对存储在Map中的键进行排序的功能。
它继承了Map接口。
实现SortedMap的类
由于SortedMap
是一个接口,我们无法直接创建它的对象。
为了使用SortedMap
接口的功能,我们需要使用实现它的TreeMap
类。
如何使用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
接口的所有方法。这是因为Map
是SortedMap
的超接口。
除了所有这些方法之外,以下是SortedMap
接口特有的方法。
- comparator() - 返回一个可用于对Map中的键进行排序的比较器
- firstKey() - 返回有序Map的第一个键
- lastKey() - 返回有序Map的最后一个键
- headMap(key) - 返回Map中所有键小于指定key的条目
- tailMap(key) - 返回Map中所有键大于或等于指定key的条目
- subMap(key1, key2) - 返回Map中键介于key1和key2之间(包括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。