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;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM