java8 list交集差集并集

时间:2025-03-09 08:18:26
import java.util.ArrayList; import java.util.List; import java.util.stream.*; import static java.util.stream.Collectors.toList; public class test { public static void main(String[] args) { List<Student> list1 = new ArrayList<Student>(); Student st1 = new Student(); st1.setId("2"); st1.setName(""); st1.setAge(""); list1.add(st1); Student sta = new Student(); sta.setId("1"); sta.setName(""); sta.setAge(""); list1.add(sta); List<Student> list2 = new ArrayList<Student>(); Student st2 = new Student(); st2.setId("3"); st2.setName(""); st1.setAge(""); list2.add(st2); // 差集 (list1 - list2) List<Student> distinctByUniqueList = list1.stream() .filter(item -> !list2.stream() .map(e -> e.getId() ) .collect(Collectors.toList()) .contains(item.getId())) .collect(Collectors.toList()); System.out.println("---差集 reduce1 (list1 - list2)---"); for(Student st : distinctByUniqueList){ System.out.println(st.getId()); System.out.println(st.getName()); } // 交集 List<Student> intersection = list1.stream() .filter(item -> list2.stream() .map(e -> e.getId()) .collect(Collectors.toList()) .contains(item.getId())) .collect(Collectors.toList()); System.out.println("---交集 intersection---"); for(Student st : intersection){ System.out.println(st.getId()); System.out.println(st.getName()); } List<Student> add1 = distinctByUniqueList.parallelStream().collect(toList()); List<Student> add2 = intersection.parallelStream().collect(toList()); add1.addAll(add2); System.out.println("---并集 listAll---"); for(Student st : add1){ System.out.println(st.getId()); System.out.println(st.getName()); } } }