java中map按值排序的方法

在学习的过程中,遇到一个问题,类似于TreeMap<String,Set<String>>,要求按照Set集合中集合的个数来对map中的key进行排序。下面说一下解决方法,由于自己新手方法可能有点笨,但是能够解决这样的问题。大体的思想就是遍历现有的map,将其复制到一个新的map中,注意复制的过程中将key和值进行调换,这样对于新的map的排序就是按照原来的值进行的排序。最后再将新的map中的数据复制到原来的map中问题就解决了。下面附上代码:

public static List<String> influencers(Map<String, Set<String>> followsGraph) {
TreeMap<Set<String>,String> newfollow = new TreeMap<Set<String>,String>(
new Comparator<Set<String>>() {
public int compare(Set<String> o1, Set<String> o2) {
int num = o2.size()-o1.size();
int num2 = num == 0?o2.toString().compareTo(o1.toString()):num;
return num2;
}
}
);
List<String> result = new ArrayList<>();
for(String key : followsGraph.keySet()) {
Set<String> value = new TreeSet<>();
value = followsGraph.get(key);
newfollow.put(value, key);
}
for(Set<String> key : newfollow.keySet()) {
result.add(newfollow.get(key));
}
return result;
}

原文地址:https://www.cnblogs.com/mrchi/p/8622430.html