packagecom.drew.test;importjava.util.List;importjava.util.Map;importcom.google.common.collect.ImmutableMap;importcom.google.common.collect.Lists;importcom.google.common.collect.Maps;/***@authorzero 2019/04/08*/
public classJava8future {public static voidmain(String[] args) {
Map map = ImmutableMap.of("0", 3, "1", 8, "0.29", 7, "1.67", 3);
System.out.println("原始的map:" +map);
System.out.println("根据map的key降序:" + sortByKey(map, true));
System.out.println("根据map的key升序:" + sortByKey(map, false));
System.out.println("根据map的value降序:" + sortByValue(map, true));
System.out.println("根据map的value升序:" + sortByValue(map, false));
}/*** 根据map的key排序
*
*@parammap 待排序的map
*@paramisDesc 是否降序,true:降序,false:升序
*@return排序好的map
*@authorzero 2019/04/08*/
public static , V> Map sortByKey(Map map, booleanisDesc) {
Map result =Maps.newLinkedHashMap();if(isDesc) {
map.entrySet().stream().sorted(Map.Entry.comparingByKey().reversed())
.forEachOrdered(e->result.put(e.getKey(), e.getValue()));
}else{
map.entrySet().stream().sorted(Map.Entry.comparingByKey())
.forEachOrdered(e->result.put(e.getKey(), e.getValue()));
}returnresult;
}/*** 根据map的value排序
*
*@parammap 待排序的map
*@paramisDesc 是否降序,true:降序,false:升序
*@return排序好的map
*@authorzero 2019/04/08*/
public static > Map sortByValue(Map map, booleanisDesc) {
Map result =Maps.newLinkedHashMap();if(isDesc) {
map.entrySet().stream().sorted(Map.Entry.comparingByValue().reversed())
.forEach(e->result.put(e.getKey(), e.getValue()));
}else{
map.entrySet().stream().sorted(Map.Entry.comparingByValue())
.forEachOrdered(e->result.put(e.getKey(), e.getValue()));
}returnresult;
}
}