lambda对两个list求差集

1,070 阅读1分钟
package com.example.filterdemo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author :yangjie
 * desc :
 * @date :2020-09-02
 **/
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
    private String name;
    private int age;

    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("tom", 20));
        studentList.add(new Student("jerry", 21));
        studentList.add(new Student("jack", 22));
        //
        List<Student> compareList = new ArrayList<>();
        compareList.add(new Student("tom", 20));
        compareList.add(new Student("jerry", 21));
        //
        List<Student> distinctByUniqueList = studentList.stream()
                .filter(item ->
                //!差集,不加就是求交集
                        !compareList.stream()
                        .map(Student::getName)
                        .collect(Collectors.toList())
                        .contains(item.getName())
                )
                .collect(Collectors.toList());
        //
        System.out.println(distinctByUniqueList);
    }
}