前置知识: Lamdba表达式 StreamApi
map根据value倒序排序
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).forEach(System.out::println);
map根据key倒序排序
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).forEach(System.out::println);
map根据value正序排序
map.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue())).forEach(System.out::println);
map根据key正序排序
map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey())).forEach(System.out::println);
结束
在实际开发中经常会用到HashMap的排序 虽然可以用TreeMap排序 但是只可以对键进行排序 用Stream可以极大提高开发效率 感觉有用就点个赞吧 如果有错误或更好的方法评论区请多多指出 相互学习共同进步 谢谢