一、map 根据value排序web
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值倒序排序,下面给出工具类:svg
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排序
想根据map的key进行排序,须要对上面的工具类进行小小的修改,代码以下:工具
public <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); 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()关键字限制去掉便可。code
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; }