java求两个集合的交集,并集和差集


 1 //求两个集合的交集,并集和差集
 2 package classwork9;
 3 
 4 import java.util.ArrayList;
 5 import java.util.Collection;
 6 import java.util.Iterator;
 7 import java.util.List;
 8 
 9 public class Jiheyunsuan {
10     List<Integer> a = new ArrayList<Integer>();
11 
12     public static Iterator<Integer> fun1(List<Integer> a, Collection<Integer> b) {
13         b.removeAll(a);
14         b.addAll(a);
15         Iterator<Integer> it = b.iterator();
16         return it;
17     }
18 
19     public static List<Integer> fun2(List<Integer> a, Collection<Integer> b) {
20         b.removeAll(a);
21         b.add(1);
22         a.removeAll(b);
23         return a;
24     }
25 
26     public static List<Integer> fun3(List<Integer> a, Collection<Integer> b) {
27         a.add(1);
28         a.retainAll(b);
29         return a;
30     }
31 
32     public 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的并集");
47         while (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);
53         for (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);
59         for (int i = 0; i < e.size(); ++i) {
60             System.out.print(e.get(i));
61         }
62     }
63 
64 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM