最近小编本身一我的在负责一个项目的后台开发,其中有一部分是统计相关的功能,因此须要一些排序或者分组的操做,以前这种操做小编以为仍是比较麻烦的,虽热有一些现成的工具类,可是工具类的写法也是比较复杂的,可是若是使用java8 stream流的话就比较简单了,而且代码量会大大的减小,下面总结几个对map的操做。java
一、map 根据value排序工具
Map<String,BigDecimal> map =new HashMap<>(); map.put("one", 0.08); map.put("two", 0.1); map.put("three", 0.2); map.put("four", 0.91);
上面是项目中的一个中间结果,咱们须要对这个map根据value值倒序排序,下面给出工具类:.net
public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); map.entrySet().stream() .sorted(Map.Entry.<K, V>comparingByValue() .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); return result; }
固然若是咱们想根据map的key进行排序,须要对上面的工具类进行小小的修改,代码以下:code
public <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();blog
map.entrySet().stream() .sorted(Map.Entry.<K, V>comparingByKey() .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); return result; }
咱们能够看到,若是咱们须要根据key排序,就须要让key 继承 Comparable ,也就说咱们须要对待排序的字段继承 Comparable接口。另外一个问题就是,上面的这种写法排序效果是 降序排序,若是咱们须要升序排序的话,只须要将上面的.reversed()关键字限制去掉便可。排序
public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();继承
map.entrySet().stream() .sorted(Map.Entry.<K, V>comparingByValue() ).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); return result; }
map根据value倒序排序接口
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).forEach(System.out::println);
map根据key倒序排序three
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).forEach(System.out::println);
map根据value正序排序ci
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);
原文连接:https://blog.csdn.net/hao134838/article/details/80780622
原文连接:https://blog.csdn.net/qq_41011894/article/details/88405944