正如我们所知,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"
是否有实现此任务的实现,还是我需要自己实现 SortedSet?