如何使用Java8Lambda表达式对两个List<Object>中的多个元素进行对比筛选
        List<Student> list = new ArrayList<>();
        List<Student> list2 = new ArrayList<>();

        Student student1 = new Student();
        student1.setAge("一");
        student1.setSex(1);

        Student student2 = new Student();
        student2.setAge("一");
        student2.setSex(2);

        Student student3 = new Student();
        student3.setAge("三");
        student3.setSex(3);

        Student student4 = new Student();
        student4.setAge("四");
        student4.setSex(4);

        // List2
        Student student5 = new Student();
        student5.setAge("一");
        student5.setSex(1);

        Student student6 = new Student();
        student6.setAge("二");
        student6.setSex(9);

        Student student7 = new Student();
        student7.setAge("三");
        student7.setSex(9);

        Student student8 = new Student();
        student8.setAge("四");
        student8.setSex(9);

现在想要的结果是筛选出两个List中age,sex都一样的元素组成一个新List


        Set<Student> s = list.stream()
                .map(
                        user -> list2.stream()
                        .filter(log -> user.getAge().equals(log.getAge()))
                        .filter(log -> user.getSex() == log.getSex())

                        .findAny()
                        .orElse(user)

                        )
                .collect(Collectors.toSet());
```                         我自己试了下好像并没有卵用

1个回答

orElse的作用是如果没有发现则返回某个值,你的代码是没有相同的时候还是返回了list中的值,实际没有做任何操作,可以把user换成null,
Set s = list.stream()
.map(
user -> list2.stream()
.filter(log -> user.getAge().equals(log.getAge()))
.filter(log -> user.getSex() == log.getSex())

                            .findAny()
                            .orElse(null)
                    )
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐