Map可以先按照value进行排序,然后按照key进行排序。 或者先按照key进行排序,然后按照value进行排序,这都是可以的。
并且,大家可以制定自己的排序规则。
下面的代码中,首先按照value的数值从大到小进行排序,当value数值大小相同时,再按照key的长度从长到短进行排序,这个操作与Stream流式操作相结合。
/**
* Map按照整数型的value进行降序排序,当value相同时,按照key的长度进行排序
*
* @param map
* @return
*/
public static LinkedHashMap<String, Integer> sortMap(Map<String, Integer> map) {
return map.entrySet().stream().sorted(((item1, item2) -> {
int compare = item2.getValue().compareTo(item1.getValue());
if (compare == 0) {
if (item1.getKey().length() < item2.getKey().length()) {
compare = 1;
} else if (item1.getKey().length() > item2.getKey().length()) {
compare = -1;
}
}
return compare;
})).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}