1、lambda对map排序
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>(16);
map.put("6", 6);
map.put("4", 4);
map.put("5", 5);
map.put("3", 3);
map.put("1", 1);
map.put("2", 2);
// 方法调用
Map<String, Integer> stringIntegerMap = mapSort(map, 0);
// 输出结果 654321
stringIntegerMap.entrySet().forEach(m -> System.out.println(m.getValue()));
}
封装方法如下:
/**
*
* @param map 需排序的map
* @param flag 0降序/1升序
* @param <K>
* @param <V>
* @return
*/
// map 进行排序 传入一个map 和 0 1
public static <K, V extends Comparable<? super V>> Map<K, V> mapSort(Map<K, V> map, int flag) {
if (flag == 1) {
return map.entrySet().stream().sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue())).map(entry -> {
Map<K, V> result = new LinkedHashMap<>();
result.put(entry.getKey(), entry.getValue());
return result;
}).reduce((map1, map2) -> {
map2.entrySet().forEach(entry -> map1.put(entry.getKey(), entry.getValue()));
return map1;
}).get();
} else {
return map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue())).map(entry -> {
Map<K, V> result = new LinkedHashMap<>();
result.put(entry.getKey(), entry.getValue());
return result;
}).reduce((map1, map2) -> {
map2.entrySet().forEach(entry -> map1.put(entry.getKey(), entry.getValue()));
return map1;
}).get();
}
}
2、lambda对list对象属性排序
升序:
List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge))
.collect(Collectors.toList());
降序:
List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge).reversed())
.collect(Collectors.toList());