import com.google.common.collect.Maps;
import java.util.Map;
/**
* @program: map排序工具类
* @description:
* @author: danrenying
* @create: 2020/7/13
**/
public class MapOrderByUtils {
/**
* @Description: 根据map的key排序
* @Author danrenying
* @Param: [map, isDesc: true:降序,false:升序]
* @Return: java.util.Map<K,V>
* @Date 2020/7/13
*/
public static <K extends Comparable<? super K>, V> Map<K, V> orderByKey(Map<K, V> map, boolean isDesc) {
if (map == null || map.isEmpty()) {
return null;
}
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;
}
}