实体类:
@Data
public class Person {
private int id;
private String name;
private String password;
}
测试:
public static void main(String[] args) {
List<Person> list1 = new ArrayList<>();
list1.add(new Person(1,"张三","123455"));
list1.add(new Person(2,"李四","2523523"));
list1.add(new Person(3,"王五","34534632"));
list1.add(new Person(4,"李六","3266236"));
List<Person> list2 = new ArrayList<>();
list2.add(new Person(2,"李四","2523523"));
list2.add(new Person(3,"王五","3346"));
list2.add(new Person(5,"马七","34654356"));
//取list1 id
List<Integer> userIds1 = list1.stream().map(Person::getId).collect(Collectors.toList());
System.out.println("---取list1 id---");
userIds1.parallelStream().forEach(System.out::println);
//取list2 id
List<Integer> userIds2 = list2.stream().map(Person::getId).collect(Collectors.toList());
System.out.println("---取list2 id---");
userIds2.parallelStream().forEach(System.out::println);
// 交集
List<Integer> intersection = userIds1.stream().filter(item -> userIds2.contains(item)).collect(toList());
System.out.println("---交集 intersection---");
intersection.parallelStream().forEach(System.out::println);
// 差集 (list1 - list2)
List<Integer> reduce1 = userIds1.stream().filter(item -> !userIds2.contains(item)).collect(toList());
System.out.println("---差集 reduce1 (list1 - list2)---");
reduce1.parallelStream().forEach(System.out::println);
// 差集 (list2 - list1)
List<Integer> reduce2 = userIds2.stream().filter(item -> !userIds1.contains(item)).collect(toList());
System.out.println("---差集 reduce2 (list2 - list1)---");
reduce2.parallelStream().forEach(System.out::println);
// 并集
List<Integer> listAll = userIds1.parallelStream().collect(toList());
List<Integer> listAll2 = userIds2.parallelStream().collect(toList());
listAll.addAll(listAll2);
System.out.println("---并集 listAll---");
listAll.parallelStream().forEachOrdered(System.out::println);
// 去重并集
List<Integer> listAllDistinct = listAll.stream().distinct().collect(toList());
System.out.println("---得到去重并集 listAllDistinct---");
listAllDistinct.parallelStream().forEachOrdered(System.out::println);
}
运行结果:
---取list1 id---
3
4
1
2
---取list2 id---
3
2
5
---交集 intersection---
3
2
---差集 reduce1 (list1 - list2)---
4
1
---差集 reduce2 (list2 - list1)---
5
---并集 listAll---
1
2
3
4
2
3
5
---得到去重并集 listAllDistinct---
1
2
3
4
5