废话不多,直接上代码:
1:新建一个实体类
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer id; private String name; }
2:准备好数据
public class tset { public static void main(String[] args) { List<Student> AList = new ArrayList<>(Arrays.asList( new Student(1,"张三"), new Student(2,"李四"), new Student(3,"王五") )); List<Student> BList = new ArrayList<>(Arrays.asList( new Student(2,"李四"), new Student(3,"王五"), new Student(4,"赵六") )); }
3:使用stream 流求
3.1 并集
Stream的concat() 方法 //并集 使用Stream的concat()方法将两个集合合并为一个流, //然后使用distinct()方法去除重复元素即可求得并集 List<Student> unionList = Stream.concat(AList.stream(), BList.stream()) .distinct() .collect(Collectors.toList()); System.out.println(unionList); 打印结果: [Student(id=1, name=张三), Student(id=2, name=李四), Student(id=3, name=王五), Student(id=4, name=赵六)]
3.2 交集
//AList 和 BList 元素交集(俩个元素中都有的元素) List<Student> studentList = AList. stream(). filter(a -> BList.stream() .map(Student::getId) .anyMatch(id -> Objects.equals(a.getId(), id))) .collect(Collectors.toList()); System.out.println("--------AList 和 BList 元素交集:"); /** * --------AList 和 BList 元素交集: * [Student(id=2, name=李四), Student(id=3, name=王五)] */ System.out.println(studentList);
3.3 差集
3.31(第一种)
//BList 和 AList 元素差集 只在B集合中存在,不在A集合中存在 List<Student> studentList1 = BList.stream() .filter(b -> AList.stream() .map(Student::getId) .noneMatch(id -> Objects.equals(b.getId(), id))) .collect(Collectors.toList()); System.out.println("BList 和 AList 元素差集:"); /** * BList 和 AList 元素差集: * [Student(id=4, name=赵六)] */ System.out.println(studentList1);
3.32(第二种)
Map<Integer, Student> map = AList.stream() .collect(Collectors.toMap(Student::getId, Function.identity(), (k1, k2) -> k2)); List<Student> studentList2 = BList.stream() .filter(b -> !map.containsKey(b.getId())).collect(Collectors.toList()); System.out.println("BList 和 AList 元素差集:"); /** * BList 和 AList 元素差集: * [Student(id=4, name=赵六)] */ System.out.println(studentList2);
4:使用Goole Guava 工程中的sets 工具包
4.1 引入依赖
<!-- google java lib --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>17.0</version> </dependency>
4.2 准备数据
HashSet<Integer> set = Sets.newHashSet(1, 2, 3, 4, 5, 6); HashSet<Integer> set2 = Sets.newHashSet( 3, 4, 5, 6,7,8,9);
4.3 并集
Sets.union()
//并集 Sets.SetView<Integer> setView2 = Sets.union(set, set2); /** * [1, 2, 3, 4, 5, 6, 7, 8, 9] */ System.out.println(setView2);
4.4 交集
Sets.intersection();
//交集 Sets.SetView<Integer> setView = Sets.intersection(set, set2); /** * [3, 4, 5, 6] */ System.out.println(setView);
4.5 差集
Sets.difference();
//差集 Sets.SetView<Integer> setView1 = Sets.difference(set, set2); /** * [1, 2] */ System.out.println(setView1);