欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java8 實(shí)現(xiàn)map以value值排序操作

 更新時間:2020年12月08日 11:14:39   作者:Haiyoung  
這篇文章主要介紹了java8 實(shí)現(xiàn)map以value值排序操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

我就廢話不多說了,大家還是直接看代碼吧~

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.LinkedHashMap;
 
public class MapSorted{
 
 public static void main(String[] args) {
  
  Map<String, Integer> map = new HashMap<>();
  map.put("A", 3);
  map.put("B", 5);
  map.put("C", 1);
  map.put("D", 1);
  map.put("E", 9);
  
  System.out.println(map);
 
  //如果value為java對象,則需要實(shí)現(xiàn)Comparable接口,重寫compareTo方法
 
  Map<String, Integer> sortedMap = new LinkedHashMap<>();
  Map<String, Integer> sortedMap2 = new LinkedHashMap<>();
 
  //ASC
  map.entrySet().stream()
   .sorted(Map.Entry.<String, Integer>comparingByValue())
   .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
 
  System.out.println(sortedMap);
 
  //DESC Collections.reverseOrder || reversed()
  map.entrySet().stream()
  .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
  .forEachOrdered(x -> sortedMap2.put(x.getKey(), x.getValue()));
 
  // map.entrySet().stream()
  // .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
  // .forEachOrdered(x -> sortedMap2.put(x.getKey(), x.getValue()));
 
  System.out.println(sortedMap2);
 
  //Collectors.toMap 直接返回排好序的map
  map = map.entrySet().stream()
     .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
     .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue(), (x1, x2) -> x2, LinkedHashMap::new));
  
  // map = map.entrySet().stream()
  // .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
  // .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x1, x2) -> x2, LinkedHashMap::new));
  System.out.println(map);
 }
}
{A=3, B=5, C=1, D=1, E=9}
{C=1, D=1, A=3, B=5, E=9}
{E=9, B=5, A=3, C=1, D=1}
{E=9, B=5, A=3, C=1, D=1}

補(bǔ)充知識:Java8-2-Lambda表達(dá)式實(shí)戰(zhàn)-一句話實(shí)現(xiàn)Map中按照Value排序

今天我們來實(shí)戰(zhàn)一把, 對Map的Value值排序進(jìn)行簡化.

在以前的思路我們的做法如下:

  /**
   * 
   * Map根據(jù)value排序;
   * 
   * @param map
   * @return
   */
  public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
      @Override
      public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
        return (o2.getValue()).compareTo(o1.getValue());
      }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list) {
      result.put(entry.getKey(), entry.getValue());
    }
    return result;
  }

什么意思呢?意思就是先把Map變成可排序的List使用Comparator接口對entry進(jìn)行排序, 可是這樣代碼很多很亂, 我們需要做一些簡化.

第一步: 使用Lambda表達(dá)式先對Comparator接口做簡化, 代碼會變成如下情況:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    
    list.sort(Comparator.comparing(Entry::getValue));

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list) {
      result.put(entry.getKey(), entry.getValue());
    }
    return result;
  }

這樣的話, 一行代碼就代替了五行, 但是會有個問題, 這樣寫只能從小到大排序很不靈活, 我們還有其他辦法.來看下面的代碼:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    
    list.sort((o1, o2)-> o2.getValue().compareTo(o1.getValue()));

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list) {
      result.put(entry.getKey(), entry.getValue());
    }
    return result;
  }

用lambda表達(dá)式就可以做到變換排序的方式, 只要改變o1和o2的順序就可以了.哎, 可以還是很長, 我還想再少幾句代碼, 怎么辦?

我們來分析下最原始的排序代碼 ---> 首先是將Map轉(zhuǎn)化為List<Entry>利用List的可排序的特性排序后遍歷到新的Map里面去, 這樣就很簡單了, 我們可以從遍歷的地方入手.代碼如下:

 public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    
    list.sort((o1, o2)-> o2.getValue().compareTo(o1.getValue()));

    Map<K, V> result = new LinkedHashMap<>();
    list.stream().forEach(entry -> result.put(entry.getKey(), entry.getValue()));
    
    return result;
  }

也許做到上面這一步已經(jīng)很滿足了, 可是作為一個優(yōu)秀的開發(fā)人員怎么能滿足于這種程度, 我們要用兩句話完成上面的功能.我們可以發(fā)現(xiàn)entrySet()是個集合, stream是有sort方法的, 可以set變成stream然后sort之后forEach到新的Map中, 牛逼吧, 廢話少說,看代碼.

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    Map<K, V> sortMap = new LinkedHashMap<>();
    new map.entrySet().stream()
        .sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue()))
        .forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
    return sortMap;
  }

高級程序員到這里就可以了, 下面提供一個工具類給大家使用.

  /**
   * flag = 1 正序
   * flag = 0 倒序
   * @param map
   * @param flag
   * @return
   */
  public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, int flag) {
    Map<K, V> sortMap = new LinkedHashMap<>();
    if(flag == 1) {
      map.entrySet().stream()
      .sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue()))
      .forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
    } else {
      map.entrySet().stream()
      .sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue()))
      .forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
    }
    return sortMap;
  }

以上的代碼已經(jīng)夠簡潔了, 但是有一個中間變量, 我作為一個究極程序員是看不慣的, 能不能把它也省略掉一句代碼實(shí)現(xiàn)整個功能呢? 答案是可以的.

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue2(Map<K, V> map, int flag) {
    
    if(flag == 1) {
      return map.entrySet().stream().sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue())).map(entry -> {
        Map<K, V> result = new LinkedHashMap<>();
        result.put(entry.getKey(), entry.getValue());
        return result;
      }).reduce((map1, map2) -> {
        map2.entrySet().forEach(entry -> map1.put(entry.getKey(), entry.getValue()));
        return map1;
      }).get();
    } else {
      return map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue())).map(entry -> {
        Map<K, V> result = new LinkedHashMap<>();
        result.put(entry.getKey(), entry.getValue());
        return result;
      }).reduce((map1, map2) -> {
        map2.entrySet().forEach(entry -> map1.put(entry.getKey(), entry.getValue()));
        return map1;
      }).get();
      
    }

思路是做好排序后將排序后的entry加入到新的Map里面, 再將stream<Map<K,V>>進(jìn)行疊加, 可能有些抽象, 不能明白的也只能幫到這啦.

以上這篇java8 實(shí)現(xiàn)map以value值排序操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論