今天群里有人问了这个问题,群里的人基本上给出的答案都是匿名内部类什么的。我给出了jdk8的写法,很简单,分享出来。

public class Main {

/**
* @Description: 把Map中的value倒序排序
* @Param: [args]
* @return: void
* @Author: YangHang
* @Date: 2019/8/24 2:15
*/
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
List<Integer> collect = map.entrySet().stream().filter(x -> x.getValue() != null).sorted((o1, o2) -> {
if (o1.getValue() < o2.getValue()) {
return 1;
}
return -1;
}).map(x -> x.getValue()).collect(Collectors.toList());
System.out.println(collect);
}
}

ps:

Comparator接口中的int compare(T o1, T o2);

如果你想把o1排在o2前面,那么你就要返回负数,证明o1小于o2,反之则返回正数,千万不要记反了。