package org.nhooo.example.util; import java.util.*; public class SortedMapDemo { public static void main(String[] args) { SortedMap<String, String> sorted = new TreeMap<>(); sorted.put("United States", "New York"); sorted.put("United Kingdom", "London"); sorted.put("Netherlands", "Amsterdam"); sorted.put("Japan", "Tokyo"); sorted.put("France", "Paris"); // 获取当前在此映射中的第一个(最低)键 String firstKey = sorted.firstKey(); // 获取当前映射中的最后一个(最高)键 String lastKey = sorted.lastKey(); System.out.println("First key: " + firstKey); System.out.println("Last key : " + lastKey); // 获取此映射范围内其键范围的视图 // 从fromKey(日本)(含)到toKey(英国), //独家。(如果fromKey和toKey相等,则返回 // 映射为空。) SortedMap<String, String> sub = sorted.subMap("Japan", "United Kingdom"); Set<String> subKeys = sub.keySet(); System.out.println("\nSub Map: "); System.out.println("============"); for (String key : subKeys) { System.out.println(key); } // 获取此映射部分的视图,其键为 // 严格小于toKey(在此示例中为荷兰) SortedMap<String, String> head = sorted.headMap("Netherlands"); Set<String> headKeys = head.keySet(); System.out.println("\nHead Map:"); System.out.println("============"); for (String key : headKeys) { System.out.println(key); } // 获取此映射部分的视图,其键为 // 严格大于或等于fromKey(在此示例中 // 是荷兰) SortedMap<String, String> tail = sorted.tailMap("Netherlands"); Set<String> tailKeys = tail.keySet(); System.out.println("\nTail Map:"); System.out.println("============"); for (String key : tailKeys) { System.out.println(key); } } }
这是程序的输出:
First key: France Last key : United States Sub Map: ============ Japan Netherlands Head Map: ============ France Japan Tail Map: ============ Netherlands United Kingdom United States