Java 集合 - 用好 SortedMap 和 NavigableMap,优化 Java 集合排序与操作效率

Java 集合 - 用好 SortedMap 和 NavigableMap,优化 Java 集合排序与操作效率
在Java中SortedMap和NavigableMap接口为Map提供了对键排序的功能。这些接口有助于管理那些需要有序存储和按特定顺序访问键值对的情况。它们通过TreeMap类的实现来工作TreeMap是一种自平衡的红黑树数据结构它保证了键的顺序。SortedMap是Map接口的扩展而NavigableMap是SortedMap的一个进一步扩展。这两个接口的实现都可以使用TreeMap类。它们都能确保键值对按照键进行排序。SortedMap和NavigableMap的功能SortedMap和NavigableMap接口通过键值对的排序为Map提供了额外的功能。下面是它们的一些重要方法和使用方法。方法概述SortedMap接口通过以下方法扩展了MapfirstKey()和lastKey()返回Map中最小和最大键。headMap(toKey)返回一个新的SortedMap其键小于toKey。tailMap(fromKey)返回一个新的SortedMap其键大于或等于fromKey。subMap(fromKey, toKey)返回一个新的SortedMap其键大于或等于fromKey且小于toKey。这些方法返回的SortedMap是原始Map的视图任何对这些视图的更改都会反映在原始Map中。值得注意的是这些视图不能插入超出原始Map范围的键。NavigableMap的附加功能NavigableMap接口提供了更多的功能包括方法navigableKeySet()它返回一个NavigableSet而不是普通的keySet()。NavigableSet提供了更多的操作例如返回下一个和上一个键。示例SortedMap的使用让我们通过一个例子来看看SortedMap和其方法如何工作SortedMapInteger, String map new TreeMap(); map.put(1, one); map.put(2, two); map.put(3, three); map.put(5, five); map.put(6, six); // 获取最小键和最大键 System.out.println(First Key: map.firstKey()); // 输出 1 System.out.println(Last Key: map.lastKey()); // 输出 6 // 获取键小于3的部分 SortedMapInteger, String headMap map.headMap(3); headMap.forEach((key, value) - System.out.println(key :: value)); // 获取键大于或等于3的部分 SortedMapInteger, String tailMap map.tailMap(3); tailMap.forEach((key, value) - System.out.println(key :: value)); // 获取键在3到5之间的部分 SortedMapInteger, String subMap map.subMap(3, 6); subMap.forEach((key, value) - System.out.println(key :: value));运行结果First Key: 1 Last Key: 6 1 :: one 2 :: two 3 :: three 3 :: three 5 :: five 6 :: six 3 :: three 4 :: four 5 :: five错误处理示例SortedMap和NavigableMap返回的视图在修改时有一些限制。比如我们通过headMap()方法创建了一个视图并试图向这个视图插入一个不在范围内的键这会导致IllegalArgumentException异常。SortedMapInteger, String headMap map.headMap(3); headMap.put(0, zero); // 这个是合法的因为 0 3 headMap.put(4, four); // 这个会抛出 IllegalArgumentException 异常因为 4 不在 headMap 范围内解释headMap(3)返回一个只包含小于3的键的SortedMap视图。因此向该视图插入键值对(4, four)会抛出异常因为4超出了headMap的键范围。但插入(0, zero)是合法的因为0小于3。通过Comparator控制排序与SortedSet和NavigableSet类似SortedMap和NavigableMap的键必须实现Comparable或者你可以在创建TreeMap时提供一个Comparator来决定键的排序方式。如果提供了Comparator即使键实现了ComparableComparator也会被优先使用。TreeMapInteger, String map new TreeMap(Comparator.reverseOrder()); map.put(1, one); map.put(2, two); map.put(3, three); map.forEach((key, value) - System.out.println(key :: value));运行结果3 :: three 2 :: two 1 :: one总结SortedMap和NavigableMap提供了对键排序的强大支持能够按顺序查询键并对部分键集合进行操作。通过headMap(),tailMap(),subMap()等方法你可以方便地获取按顺序划分的Map视图并对这些视图进行修改。NavigableMap提供了更多的方法例如navigableKeySet()让你可以获得更多基于顺序操作的功能。在使用视图时要注意不可以插入不在视图范围内的键。通过这些方法和特性SortedMap和NavigableMap能够帮助你更高效地处理排序和部分视图的需求是构建有序Map数据结构的理想选择。