Java stream流处理常用操作

去空去重:

List<Course> courses = ...;
List<Long> courseNumbers = courses.stream().filter(Ojects::nonNull).map(Course::getNumber).distinct().collect(Collectors.toList());

多条件排序:

List<ClazzLesson> toBeSorted = ...;
// 先按开始时间排序后按number排序
List<ClazzLesson> sorted = toBeSorted.stream().sorted(Comparator.comparing(ClazzLesson::getBeginTime).thenComparing(ClazzLesson::getNumber))
                .collect(Collectors.toList())

将list转化成特定key的map

Map<Integer,ITaskTransfer> map = taskTransferList.stream().collect(Collectors.toMap(ITaskTransfer::getOperateCode,t -> t))

根据ClazzLesson的list进行某个字段的group操作生成key为ClazzLesson.getClazzNumber()、value为List<ClazzLesson> 的Map:

List<ClazzLesson> lessons = ...;
Map<Long,List<ClazzLesson>> num2Lesson = lessons.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(ClazzLesson::getClazzNumber));

根据Tag的list对Tag.getClazzNumber()进行group操作,生成key为Tag.getClazzNumber()、value为List<Tag.getId()>的map:

List<Tag> tags=...;
Map<Long, List<Integer>> clazzNum2TagIds = tags.stream().filter(Objects::nonNull).collect(
                Collectors.groupingBy(Tag::getClazzNumber,
                        Collectors.mapping(Tag::getId, Collectors.toList())));

聚合后找到最大UpdateTime并生成map

Map<Long, Optional<NumberAndUpdateTimeVO>> optionalMap =
                numberAndUpdateTimeList.stream().filter(r -> Objects.nonNull(r.getUpdateTime()))
                        .collect(Collectors.groupingBy(NumberAndUpdateTimeVO::getNumber, Collectors.maxBy(
                                Comparator.comparing(NumberAndUpdateTimeVO::getUpdateTime))));

猜你喜欢

转载自blog.csdn.net/weixin_41866717/article/details/130677198