java8 stream中使用分组排序 分组获取最大、最小值;
实体类中 list列表中分组排序
实体类
@Data
@Accessors(chain = true)
public class Users {
private Integer age;
private String name;
private Integer sex;
}
分组后排序
Map<String, List<Users>> sortUsers = objects.stream()
.collect(Collectors.groupingBy(Users::getName, CommonUtils.toSortedList(
Comparator.comparing(Users::getAge)
.reversed())));
//收集器
public static <T> Collector<T, ?, List<T>> toSortedList(Comparator<? super T> c) {
return Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(c)), ArrayList::new);
}
分组后获取最大、最小实体
Map<String, Users> sortUsersMax = objects.stream()
.collect(Collectors.groupingBy(Users::getName, CommonUtils.toSorted(Comparator.comparing(Users::getAge))));
//收集器 如果获取最小值 Collectors.maxBy(c) -》 Collectors.minBy(c)
public static <T> Collector<T, ?, T> toSorted(Comparator<? super T> c) {
Collector<T, ?, T> usersObjectUsersCollector = Collectors.collectingAndThen(Collectors.maxBy(c), Optional::get);
return usersObjectUsersCollector;
}
重构分组key 以及value
//获取省市映射关系
Map<String, List<String>> pCityDataMap = cityValues.stream()
.collect(Collectors.groupingBy(k ->
Optional.ofNullable(pCodeName.get(k.getPCode()))
.orElse(Integer.toString(-1)),
Collectors.mapping(CityDto::getName,
Collectors.toList())));
//获取市区映射关系
Map<String, List<String>> cAreaDataMap = areaValues.stream()
.collect(Collectors.groupingBy(k -> Optional.ofNullable(cCodeName.get(k.getCCode()))
.orElse(Integer.toString(-1)),
Collectors.mapping(AreaDto::getName,
Collectors.toList())));
网友评论