怎么在网上找做网站的客户,网站建设项目计划,线下推广方式都有哪些,网站备案网站负责人前言#xff1a; TreeMap普通的排序方法都是根据键来比较来排序#xff0c;本篇文章实现两种方式实现值排序 1.使用 SortedSet 和 Stream API
如果你想要一个持久化的排序结果#xff0c;你可以使用 SortedSet 结构来存储键值对的条目。
TreeSetMap.EntryString, … 前言 TreeMap普通的排序方法都是根据键来比较来排序本篇文章实现两种方式实现值排序 1.使用 SortedSet 和 Stream API
如果你想要一个持久化的排序结果你可以使用 SortedSet 结构来存储键值对的条目。
TreeSetMap.EntryString, 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.EntryString, 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 ComparablePerson {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;}
}// 使用反向映射
TreeMapString, 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.EntryString, Person entry : reverseMap.entrySet()) {System.out.println(entry.getKey() : entry.getValue());
}// 现在我们想按 Person 的 name 排序
TreeMapPerson, String mapByValue new TreeMap(Comparator.naturalOrder());// 将键值对反转
for (Map.EntryString, Person entry : reverseMap.entrySet()) {mapByValue.put(entry.getValue(), entry.getKey());
}// 打印按 Person 的 name 排序后的映射
for (Map.EntryPerson, String entry : mapByValue.entrySet()) {System.out.println(entry.getKey() : entry.getValue());
}