众所周知,SortedMap 维护按键排序的条目。我在这个论坛上阅读了很多帖子,并看到了很多按值对 SortedMap 进行排序的示例。但是,正如您所知,当我将一个项目放入默认的 SortedMap 时,它不会再次对 Map 进行排序,只是将这个新条目放在它应该在的位置。
例如,
SortedMap<String,Person> sortedMap = new TreeMap();
Person p1 = new Person("John",38);
sortedMap.put(p1.getName(), p1);
Person p2 = new Person("Tom",34);
sortedMap.put(p2.getName(), p2); // does not sort, maintains sorted set by comparing the other values
Person p3 = new Person("Susan",21);
sortedMap.put(p3.getName(), p3); // does not sort, maintains sorted set by comparing the other values
在这个论坛的许多线程中,我看到很多代码通过调用排序方法按值对 SortedMap 进行排序,例如:
sortedMap.sort(sortedMap.entries());
正在调用此方法或其他方法来获取已排序的值。
但是,我需要一个 Map 实现,它可以使值保持排序,而不需要调用排序方法,正如我在上面解释的那样。例如,在上面的代码中我可以调用firstKey()方法;但我需要调用firstValue() 方法。
Person minimumAgePerson = sortedMap.firstValue().
System.out.println(minimumAgePerson.getName()); // it should print "Susan"
SortedSet 不适合我的要求,因为我可以放置一些新对象( Person ),其键值已经在映射中,这些刚刚添加的条目应该覆盖现有对象(所以我需要一个映射):
Person p4 = new Person("Susan",39);
sortedMap.put(p4.getName(),p4);
Person newMinimumAgePerson = sortedMap.firstValue();
System.out.println(newMinimumAgePerson.getName()); // it should print "Tom"
是否有实现来完成此任务,或者我需要自己实现排序集?