The intersection, union, and difference of sets are often solved in projects. Here’s a note. Start by creating two collections list1, list2, and add elements.

List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
List<String> list2 = new ArrayList<>();
list2.add("b");
list2.add("c");
Copy the code

intersection

list1.retainAll(list2);
Copy the code

Union (deduplication)

list1.removeAll(list2);
list1.addAll(list2);
Copy the code

Union (without deduplicating)

list1.addAll(list2);
Copy the code

The difference set list1 has, list2 does not

list1.removeAll(list2);
Copy the code