1.方法介绍
Map.Entry.comparingByValue():根据value
Map.Entry.comparingByKey():根据key
2.具体代码
package com.zyp.test;
import com.google.common.collect.Maps;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author syl
* @description map的stream流使用
* @since 2021/4/19
*/
public class StreamMap {
public static void main(String[] args) {
Map<String,Integer> map= Maps.newHashMap();
map.put("d",4);
map.put("e",5);
map.put("f",1);
map.put("b",2);
map.put("c",3);
//根据key排序
map.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue,newValue)->oldValue, LinkedHashMap::new)).
forEach((K,V)-> System.out.println(K+":"+V));
//根据value排序
System.out.println("------------------------------------");
map.entrySet().stream().sorted(Map.Entry.comparingByValue(Integer::compareTo)).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue,newValue)->oldValue, LinkedHashMap::new)).
forEach((K,V)-> System.out.println(K+":"+V));
}
}