说明:使用stream().map().collect()方法提取出一个List中某个属性的集合,随后使用stream().filter(item->list.contains(args)).collect()方法,筛选出包含所提取属性的集合。
//两个list集合取交集
List<Student> intersection = newList.stream().filter(item -> oldList.stream()
.map(Student::getStudentCode).collect(Collectors.toList())
.contains(item.getStudentCode()))
.collect(Collectors.toList());
打印值:[Student(id=1, name=张三, age=21), Student(id=3, name=王五, age=23)]
说明:与求集的方法基本相同,在oldList前取反即可。此处对newList取差集,如需对oldList取差集,两个集合互换位置即可。
//两个list集合取差集
List<Student> difference = newList.stream().filter(item -> !oldList.stream()
.map(Student::getStudentCode).collect(Collectors.toList())
.contains(item.getStudentCode()))
.collect(Collectors.toList());
打印值:[Student(id=2, name=李四, age=22)
说明:与单个属性求交集方法相同,可通过"&"拼接其余属性来实现
//多属性交集
List<Student> multIntersection = newList.stream().filter(item -> oldList.stream()
.map(stu->stu.getId()+"&"+stu.getAge()).collect(Collectors.toList())
.contains(item.getId()+"&"+item.getAge()))
.collect(Collectors.toList());
打印值:[Student(id=1, name=张三, age=21), Student(id=3, name=王五, age=23)]
说明:与多个属性交集相同,在oldList前取反即可
//多属性差集
List<Student> multDifference = newList.stream().filter(item -> !oldList.stream()
.map(stu->stu.getId()+"&"+stu.getAge()).collect(Collectors.toList())
.contains(item.getId()+"&"+item.getAge()))
.collect(Collectors.toList());
打印值:[Student(id=2, name=李四, age=22)]
@Data
@AllArgsConstructor
@NoArgsConstructor
class Student{
//学号
private String id;
//姓名
private String name;
//年龄
private String age;
}
public class Test {
public static void main(String[] args) {
List<Student> newList=new ArrayList<>();
List<Student> oldList=new ArrayList<>();
newList.add(new Student("1","张三","21"));
newList.add(new Student("2","李四","22"));
newList.add(new Student("3","王五","23"));
oldList.add(new Student("1","张三","21"));
oldList.add(new Student("3","赵六","23"));
//单属性交集
List<Student> intersection = newList.stream().filter(item -> oldList.stream()
.map(Student::getId).collect(Collectors.toList())
.contains(item.getId()))
.collect(Collectors.toList());
System.out.println(intersection);
//单属性差集
List<Student> difference = newList.stream().filter(item -> !(oldList.stream()
.map(Student::getId).collect(Collectors.toList()))
.contains(item.getId()))
.collect(Collectors.toList());
System.out.println(difference);
//多属性交集
List<Student> multIntersection = newList.stream().filter(item -> oldList.stream()
.map(stu->stu.getId()+"&"+stu.getAge()).collect(Collectors.toList())
.contains(item.getId()+"&"+item.getAge()))
.collect(Collectors.toList());
System.out.println(multIntersection);
//多属性差集
List<Student> multDifference = newList.stream().filter(item -> !oldList.stream()
.map(stu->stu.getId()+"&"+stu.getAge()).collect(Collectors.toList())
.contains(item.getId()+"&"+item.getAge()))
.collect(Collectors.toList());
System.out.println(multDifference);
}
}