I used the difference set of lists in my work, and found it to be quite useful.
So record it.
need | list method | illustrate | Remark |
---|---|---|---|
intersection | listA.retainAll(listB) | The content of listA becomes an object where both listA and listB exist | listB does not change |
difference | listA.removeAll(listB) | Deduplication of the content of listB that exists in listA | listB does not change |
union | listA.removeAll(listB) listA.addAll(listB) |
In order to remove duplicates, listA first takes the difference, and then appends all listB | listB does not change |
Test code:
// 交集
List<String> listA_01 = new ArrayList<String>(){{
add("A");
add("B");
}};
List<String> listB_01 = new ArrayList<String>(){{
add("B");
add("C");
}};
listA_01.retainAll(listB_01);
System.out.println(listA_01); // 结果:[B]
System.out.println(listB_01); // 结果:[B, C]
// 差集
List<String> listA_02 = new ArrayList<String>(){{
add("A");
add("B");
}};
List<String> listB_02 = new ArrayList<String>(){{
add("B");
add("C");
}};
listA_02.removeAll(listB_02);
System.out.println(listA_02); // 结果:[A]
System.out.println(listB_02); // 结果:[B, C]
// 并集
List<String> listA_03 = new ArrayList<String>(){{
add("A");
add("B");
}};
List<String> listB_03 = new ArrayList<String>(){{
add("B");
add("C");
}};
listA_03.removeAll(listB_03);
listA_03.addAll(listB_03);
System.out.println(listA_03); // 结果:[A, B, C]
System.out.println(listB_03); // 结果:[B, C]