java求两个集合的交集和并集
java如何求两个集合的交集和并集呢??其实java的API中已经封装了方法。今天写个简单的例子测试一下:(例子中以java.util.LinkedList为例)
求连个集合的交集:
import java.util.ArrayList;import java.util.List;public class TestCollection { public static void main(String[] args) { ListstrList = new ArrayList (); List strList2 = new ArrayList (); for(int i = 0; i < 10; i ++) { strList.add("aaa>>" + i); strList2.add("aaa>>" + (10 - i)); } //求出交集 strList2.retainAll(strList); System.out.println("交集大小:" + strList2.size()); for(int i = 0; i < strList2.size(); i++) { System.out.println(strList2.get(i)); } }}
求两个集合的并集:
import java.util.ArrayList;import java.util.List;public class TestCollection { public static void main(String[] args) { ListstrList = new ArrayList (); List strList2 = new ArrayList (); for(int i = 0; i < 10; i ++) { strList.add("aaa>>" + i); strList2.add("aaa>>" + (10 - i)); } //求出并集 strList2.removeAll(strList); strList2.addAll(strList); System.out.println("并集大小:" + strList2.size()); for(int i = 0; i < strList2.size(); i++) { System.out.println(strList2.get(i)); } }}
例子非常简单,希望对大家有帮助!!!