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