零、公共部分
private static class InitLists {
private List<String> list1;
private List<String> list2;
public List<String> getList1() {
return list1;
}
public List<String> getList2() {
return list2;
}
public InitLists invoke() {
list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
list2 = new ArrayList<>();
list2.add("C");
list2.add("B");
return this;
}
}```
## 一、并集
```java
public static void testBingJi(){
InitLists initLists = new InitLists().invoke();
List<String> list1 = initLists.getList1();
List<String> list2 = initLists.getList2();
//包含重复的并集
list1.addAll(list2);
System.out.println(list1);
}
二、交集
public static void testJiaoJi(){
InitLists initLists = new InitLists().invoke();
List<String> list1 = initLists.getList1();
List<String> list2 = initLists.getList2();
//交集
list1.retainAll(list2);
System.out.println(list1);
}
三、差集
public static void testChaJi(){
InitLists initLists = new InitLists().invoke();
List<String> list1 = initLists.getList1();
List<String> list2 = initLists.getList2();
//差集
list1.removeAll(list2);
System.out.println(list1);
}
四、无重复的并集
public static void testBingJiNoRepeat(){
InitLists initLists = new InitLists().invoke();
List<String> list1 = initLists.getList1();
List<String> list2 = initLists.getList2();
//无重复的并集
list2.removeAll(list1);
list1.addAll(list2);
System.out.println(list1);
}
五、测试
public static void main(String[] args) {
testBingJi();
testJiaoJi();
testChaJi();
testBingJiNoRepeat();
}
六、结果
[A, B, C, B]
[B]
[A]
[A, B, C]