1.有時候有兩個list物件,我們想要去重,比如:
List<User> userList和List<Person>personList
想通過User的id和Person的id進行去重,去掉userList中的User的id不等於personList中的Person的id的物件。
List<User> userList= userList.stream()
.filter(user-> !personList.stream()
.map(person ->person.getId())
.collect(Collectors.toList())
.contains(user.getId()))
// .filter(UniqueUtils.distinctByKey(person ->person.getId()))
// .peek(person -> person .setId(UUIDUtil.uuid()))
.collect(Collectors.toList());
// 交集
L
ist<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
System.out.println("---得到交集 intersection---");
intersection.parallelStream().forEach(System.out :: println);
// 差集 (list1 - list2)
List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
System.out.println("---得到差集 reduce1 (list1 - list2)---");
reduce1.parallelStream().forEach(System.out :: println);
// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
System.out.println("---得到差集 reduce2 (list2 - list1)---");
reduce2.parallelStream().forEach(System.out :: println);
// 並集
List<String> listAll = list1.parallelStream().collect(toList());
List<String> listAll2 = list2.parallelStream().collect(toList());
listAll.addAll(listAll2);
System.out.println("---得到並集 listAll---");
listAll.parallelStream().forEach(System.out :: println);
// 去重並集
List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
System.out.println("---得到去重並集 listAllDistinct---");
listAllDistinct.parallelStream().forEach(System.out :: println);
System.out.println("---原來的List1---");
list1.parallelStream().forEach(System.out :: println);
System.out.println("---原來的List2---");
list2.parallelStream().forEach(System.out :: println);