java8 map根据key或者value进行排序

转自:https://www.jb51.net/article/169242.htm

map根据key或者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值倒序排序,下面给出工具类:

  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进行排序,需要对上面的工具类进行小小的修改,代码如下:

 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()关键字限制去掉即可。

 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的key排序

    public static <K extends String, V> Map sortMapKey(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new ArrayList(map.entrySet());
        list.sort((o1, o2) -> o2.getKey().length() - o1.getKey().length());
        Map<K, V> linkedMap = new LinkedHashMap<>();
        //list<map>转map,博主不会,如果有大神看到,麻烦评论里教一下
        for (Map.Entry<K, V> entry : list) {
            linkedMap.put(entry.getKey(), entry.getValue());
        }
        return linkedMap;
    }