java求两个集合的交集,并集和差集
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java求两个集合的交集,并集和差集 1//求两个集合的交集,并集和差集
2package classwork9;
3
4import java.util.ArrayList;
5import java.util.Collection;
6import java.util.Iterator;
7import java.util.List;
8
9public class Jiheyunsuan {
10 List<Integer> a = new ArrayList<Integer>();
11
12public static Iterator<Integer> fun1(List<Integer> a, Collection<Integer> b) {
13 b.removeAll(a);
14 b.addAll(a);
15 Iterator<Integer> it = b.iterator();
16return it;
17 }
18
19public static List<Integer> fun2(List<Integer> a, Collection<Integer> b) {
20 b.removeAll(a);
21 b.add(1);
22 a.removeAll(b);
23return a;
24 }
25
26public static List<Integer> fun3(List<Integer> a, Collection<Integer> b) {
27 a.add(1);
28 a.retainAll(b);
29return a;
30 }
31
32public static void main(String[] args) {
33 List<Integer> a = new ArrayList<Integer>();
34 a.add(1);
35 a.add(2);
36 a.add(3);
37 a.add(4);
38 Collection<Integer> b = new ArrayList<Integer>();
39 b.add(1);
40 b.add(3);
41 b.add(5);
42 b.add(7);
43 b.add(9);
44 b.add(11);
45 Iterator<Integer> it = fun1(a, b);
46 System.out.println("集合a与b的并集");
47while (it.hasNext()) {
48 System.out.print(it.next() + " ");
49 }
50 System.out.println();
51 System.out.println("a-b=");
52 List<Integer> d = fun2(a, b);
53for (int x : d) {
54 System.out.print(x + " ");
55 }
56 System.out.println();
57 System.out.println("集合a与b的交集");
58 List<Integer> e = fun3(a, b);
59for (int i = 0; i < e.size(); ++i) {
60 System.out.print(e.get(i));
61 }
62 }
63
64 }。