[Stream]自定义的Collect筛选

2023-12-14 19:44:49

?这里使用map就是让map中的内容作用到s上去

然后我们在map(s->{})中的部分完成了筛选 并且返回一个Actor类型的值

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        // 1. 创建两个ArrayList的集合
        ArrayList<String> manList = new ArrayList<>();
        ArrayList<String> womenList = new ArrayList<>();

        // 2. 添加数据
        Collections.addAll(manList, "蔡徐坤,24", "叶齁咸,23", "刘不甜,22", "吴签,24", "谷嘉,30", "肖梁梁,27");
        Collections.addAll(womenList, "赵小颖,35", "杨颖,36", "高元元,43", "张天天,31", "刘诗,35", "杨小幂,33");

        // 3. 筛选男演员
        Stream<String> stream1 = manList.stream()
                .filter(s -> s.split(",")[0].length() == 3)
                .limit(2);

        // 4. 筛选女演员
        Stream<String> stream2 = womenList.stream()
                .filter(s -> s.split(",")[0].startsWith("杨"))
                .skip(1);

        // 5. 合并演员名字并封装为Actor对象
        List<Actor> actorList = Stream.concat(stream1, stream2)
                .map(s -> {
                    String name = s.split(",")[0];
                    int age = Integer.parseInt(s.split(",")[1]);
                    return new Actor(age,name);
                })
                .collect(Collectors.toList());

        // 6. 打印结果
        for (Actor actor : actorList) {
            System.out.println(actor);
        }
    }
}

文章来源:https://blog.csdn.net/qq_37511412/article/details/135001878
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。