List和set集合:交集、差集、合集的區別retainAll,removeAll、addAll
set 、list集合的交集(retainAll)、差集(removeAll)是沒有區別的都是一樣的.
set 、list集合的合集addAll是有區別的:set可以去重複;list不去重複
public static void main(String[] args) {
Set<Integer> result = new HashSet<Integer>();
Set<Integer> set1 = new HashSet<Integer>(){{
add(1);
add(3);
add(5);
}};
Set<Integer> set2 = new HashSet<Integer>(){{
add(1);
add(2);
add(3);
}};
result.clear();
result.addAll(set1);
System.out.println("去重複交集前1:"+set1);
System.out.println("去重複交集前2:"+set2);
result.retainAll(set2);
System.out.println("set1與set2的交集是:"+result);
result.clear();
result.addAll(set2);
System.out.println("差集前的1:"+set1);
System.out.println("差集前的2:"+set2);
result.removeAll(set1);
System.out.println("set2與set1的差集是:"+result);
result.clear();
result.addAll(set1);
result.addAll(set2);
System.out.print("set1和set2的並集:"+result);
System.err.print("set1集合並集:是去重複"+"\n");
List<Integer> list = new ArrayList<Integer>();
List<Integer> list1 = new ArrayList<Integer>(){{
add(1);
add(3);
add(5);
}};
List<Integer> list2 = new ArrayList<Integer>(){
{
add(1);
add(2);
add(3);
}};
list.clear();
list.addAll(list1);
System.out.println("去重複交集前1:"+list1);
System.out.println("去重複交集前2:"+list2);
list.retainAll(list2);
System.out.println("list1與list2的交集是:"+list);
list.clear();
list.addAll(list2);
System.out.println("差集前的1:"+list1);
System.out.println("差集前的2:"+list2);
list.removeAll(list1);
System.out.println("list2與list1的差集是:"+list);
list.clear();
list.addAll(list1);
list.addAll(list2);
System.out.print("list1和set2的並集:"+list);
System.err.print("List集合並集:是不會去重複");
}
輸出結果:
去重複交集前1:[1, 3, 5]
去重複交集前2:[1, 2, 3]
set1與set2的交集是:[1, 3]
差集前的1:[1, 3, 5]
差集前的2:[1, 2, 3]
set2與set1的差集是:[2]
set1和set2的並集:[1, 2, 3, 5]set1集合並集:是去重複
去重複交集前1:[1, 3, 5]
去重複交集前2:[1, 2, 3]
list1與list2的交集是:[1, 3]
差集前的1:[1, 3, 5]
差集前的2:[1, 2, 3]
list2與list1的差集是:[2]
list1和set2的並集:[1, 3, 5, 1, 2, 3]List集合並集:是不會去重複