Not much nonsense, let’s go directly to the code:
Table of contents
4: Use the sets toolkit in the Goole Guava project
1: Create a new entity class
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer id;
private String name;
}
2: Prepare the data
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: Use stream flow request
3.1 Union
Stream's concat() method
//并集 使用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 Intersection
//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 Difference set
3.31 (first type)
//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 (second type)
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: Use the sets toolkit in the Goole Guava project
4.1 Introducing dependencies
<!-- google java lib -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>17.0</version>
</dependency>
4.2 Prepare data
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 Union
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 Intersection
Sets.intersection();
//交集
Sets.SetView<Integer> setView = Sets.intersection(set, set2);
/**
* [3, 4, 5, 6]
*/
System.out.println(setView);
4.5 Difference set
Sets.difference();
//差集
Sets.SetView<Integer> setView1 = Sets.difference(set, set2);
/**
* [1, 2]
*/
System.out.println(setView1);