1、key排序
/**
* 使用 Map按key进行排序
*
* @param unSortMap
* @return
*/
public static Map<String, String> SortByKey(Map<String, String> unSortMap) {
Map<String, String> result = unSortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
return result;
}
2、value排序
/**
* 使用 Map按value进行排序
*
* @param unSortMap
* @return
*/
public static Map<String, String> sortByValueDesc(Map<String, String> unSortMap) {
Map<String, String> result = unSortMap.entrySet().stream()
.sorted(Map.Entry.<String, String>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
return result;
}
public static Map<String, String> sortByValueAsc(Map<String, String> unSortMap) {
Map<String, String> result = unSortMap.entrySet().stream()
.sorted(Map.Entry.<String, String>comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
return result;
}