Java stream stream processing common operations

To empty and deduplicate:

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

Multi-condition sorting:

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

Convert the list into a map with a specific key

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

According to the ClazzLesson list, perform a group operation on a certain field to generate a Map whose key is ClazzLesson.getClazzNumber() and whose value is List<ClazzLesson>:

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

Perform a group operation on Tag.getClazzNumber() according to the list of Tags to generate a map whose key is Tag.getClazzNumber() and value is List<Tag.getId()>:

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

Find the maximum UpdateTime after aggregation and generate a 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))));

Guess you like

Origin blog.csdn.net/weixin_41866717/article/details/130677198