package com.ws.ldy.common.utils;
import com.google.common.collect.Maps;
import java.util.Map;
/**
* jdk 8 排序工具类
* @author wangsong
* @mail 1720696548@qq.com
* @date 2020/9/14 0014 14:19
* @version 1.0.0
*/
public class Java8MapSort {
/**
* 根据map的key排序
*
* @param map 待排序的map
* @param isDesc 是否降序,true:降序,false:升序
* @return 排序好的map
* @author zero 2019/04/08
*/
public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean isDesc) {
Map<K, V> result = Maps.newLinkedHashMap();
if (isDesc) {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
/**
* 根据map的value排序
*
* @param map 待排序的map
* @param isDesc 是否降序,true:降序,false:升序
* @return 排序好的map
* @author zero 2019/04/08
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean isDesc) {
Map<K, V> result = Maps.newLinkedHashMap();
if (isDesc) {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed())
.forEach(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
}
-
个人开源项目(通用后台管理系统)–> https://gitee.com/wslxm/spring-boot-plus2 , 喜欢的可以看看
-
本文到此结束,如果觉得有用,动动小手点赞或关注一下呗,将不定时持续更新更多的内容…,感谢大家的观看!