1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
public class CollectionTest { public static void main(String[] args) {
Set<Integer> set1 = new HashSet<Integer>() { { add(1); add(3); add(5); } };
Set<Integer> set2 = new HashSet<Integer>() { { add(1); add(2); add(3); } };
Set<Integer> result = new HashSet<>();
result.addAll(set1); System.out.println("set1:" + set1); System.out.println("set2:" + set2); result.retainAll(set2); System.out.println("set1与set2的交集是: " + result);
result.clear(); result.addAll(set2); result.removeAll(set1); System.out.println("set2与set1的差集是: " + result);
result.clear(); result.addAll(set1); result.addAll(set2);
System.out.println("set1和set2的并集: " + result); System.out.println("set集合并集,是去重复的");
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<Integer> list = new ArrayList<>();
list.addAll(list1); System.out.println("list1: " + list1); System.out.println("list2: " + list2); list.retainAll(list2); System.out.println("list1与list2的交集是: " + list);
list.clear(); list.addAll(list2); list.removeAll(list1); System.out.println("list2与list1的差集是:" + list);
list.clear(); list.addAll(list1); list.addAll(list2);
System.out.println("list1和list2的并集: " + list); System.out.println("List集合并集, 是不去重复的");
} }
set1:[1, 3, 5] set2:[1, 2, 3] set1与set2的交集是: [1, 3] set2与set1的差集是: [2] set1和set2的并集: [1, 2, 3, 5] set集合并集,是去重复的 list1: [1, 3, 5] list2: [1, 2, 3] list1与list2的交集是: [1, 3] list2与list1的差集是:[2] list1和list2的并集: [1, 3, 5, 1, 2, 3] List集合并集, 是不去重复的
|