您应该使用无序的HashMap,然后每次要排序时,使用将HashMap作为变量的Comparator将HashMap的所有值放入TreeMap中。
然后,对于您比较的每个键,您将获得HashMap(列表)的值并检查列表大小。因此,您可以按列表大小进行比较,根据具体情况返回-1,0或1。
完成所需后,您将丢弃该TreeMap。
如果您尝试仅使用TreeMap,那么您将看到您根据不是此类键属性的值来排序键。在这种情况下,值的长度(列表)。因此,可能存在一个增加列表长度的函数,而TreeMap甚至都不会注意到。
一些代码:
public class ListSizeComparator implements Comparator {
private final Map> map;
public ListSizeComparator(final Map> map) {
this.map = map;
}
@Override
public int compare(String s1, String s2) {
//Here I assume both keys exist in the map.
List list1 = this.map.get(s1);
List list2 = this.map.get(s2);
Integer length1 = list1.size();
Integer length2 = list2.size();
return length1.compareTo(length2);
}
}