TreeMap实现根据值比较
前言:
TreeMap普通的排序方法都是根据键来比较来排序,本篇文章实现两种方式实现值排序
1.使用 SortedSet 和 Stream API
如果你想要一个持久化的排序结果,你可以使用 SortedSet
结构来存储键值对的条目。
TreeSet<Map.Entry<String, Person>> set = new TreeSet<>(Map.Entry.comparingByValue());set.add(new AbstractMap.SimpleEntry<>("A", new Person("Alice", 25)));
set.add(new AbstractMap.SimpleEntry<>("B", new Person("Bob", 20)));
set.add(new AbstractMap.SimpleEntry<>("C", new Person("Charlie", 30)));// 打印排序后的条目
for (Map.Entry<String, Person> entry : set) {System.out.println(entry.getKey() + ": " + entry.getValue());
}
这里的
Map.Entry.comparingByValue()
方法是根据映射条目的值 (value
) 进行排序。这个方法返回一个Comparator
实例,该实例会比较Map.Entry
对象中的值。
2. 使用反向映射
如果你只需要临时性的根据值进行排序,并且值的类型实现了 Comparable
接口或者你可以提供一个适当的 Comparator
,那么可以创建一个反向映射,即把原来的键值对反转过来。
// 假设我们有一个 Person 类,其中的 name 属性实现了 Comparable 接口
class Person implements Comparable<Person> {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public int getAge() {return age;}@Overridepublic int compareTo(Person other) {return this.name.compareTo(other.name); // 按名字排序}@Overridepublic String toString() {return name + ":" + age;}
}// 使用反向映射
TreeMap<String, Person> reverseMap = new TreeMap<>();reverseMap.put("A", new Person("Alice", 25));
reverseMap.put("B", new Person("Bob", 20));
reverseMap.put("C", new Person("Charlie", 30));// 打印反转后的映射
for (Map.Entry<String, Person> entry : reverseMap.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());
}// 现在我们想按 Person 的 name 排序
TreeMap<Person, String> mapByValue = new TreeMap<>(Comparator.naturalOrder());// 将键值对反转
for (Map.Entry<String, Person> entry : reverseMap.entrySet()) {mapByValue.put(entry.getValue(), entry.getKey());
}// 打印按 Person 的 name 排序后的映射
for (Map.Entry<Person, String> entry : mapByValue.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());
}