一、找到2个集合中相同和不同的元素 此处需要使用Collection集合所提供的一个方法:removeAll(Cellection list) 实现代码如下: import Java.util.ArrayList; import java.util.Collection; import java.util.List; public class Test { public static void main(String args[]){ //集合一 List<String> _first=new ArrayList<String>(); _first.add("jim"); _first.add("tom"); _first.add("jack"); //集合二 List<String> _second=new ArrayList<String>(); _second.add("jack"); _second.add("happy"); _second.add("sun"); _second.add("good"); Collection exists=new ArrayList<String>(_second); Collection notexists=new ArrayList<String>(_second); exists.removeAll(_first); System.out.println("_second中不存在于_set中的:"+exists); notexists.removeAll(exists); System.out.println("_second中存在于_set中的:"+notexists); } } 结果: _second中不存在于_set中的元素:[happy, sun, good] _second中存在于_set中的元素:[jack] 二、去除List中的重复元素(此处只举最简单、常用的方法) 利用HashSet元素不重复的特性(如果泛型是对象,那么需要实现equals和hashCode方法) @Test public void testOtherList(){ //新建List集合 List nowList=new ArrayList(); //加入元素 nowList.add(1); nowList.add(2); nowList.add(2); nowList.add(55); nowList.add(3); nowList.add(1); nowList.add(56); nowList.add(56); //利用HashSet元素不重复的特性 nowList=new ArrayList(new HashSet(nowList)); System.out.println("去除重复数据后的集合:"+nowList); 结果打印:去除重复数据后的集合:[1, 2, 3, 55, 57, 56] } 三、操作集合,求交集、并集和差集 编写类:FindNumber.java package day0527; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @ClassName: FindNumber * @Description: A={6,3,9,3,2,4,5,7},B={5,8,6,2,1,9},则输出3,4,7,1,8 思路:全集除掉交集,就是结果 * @author * @date 2016年5月27日 上午9:56:25 * */ public class FindNumber { public static void main(String[] args) { // 注意:一定要使用创建对象的格式创建数组 Integer[] a = new Integer[] { 6, 3, 9, 3, 2, 4, 5, 7 }; Integer[] b = new Integer[] { 5, 8, 6, 2, 1, 9 }; List _a = Arrays.asList(a); List _b = Arrays.asList(b); // 创建集合 Collection realA = new ArrayList<Integer>(_a); Collection realB = new ArrayList<Integer>(_b); // 求交集 realA.retainAll(realB); System.out.println("交集结果:" + realA); Set result = new HashSet(); // 求全集 result.addAll(_a); result.addAll(_b); System.out.println("全集结果:" + result); // 求差集:结果 Collection aa = new ArrayList(realA); Collection bb = new ArrayList(result); bb.removeAll(aa); System.out.println("最终结果:" + bb); /** * 交集结果:[6, 9, 2, 5] 全集:[1, 2, 3, 4, 5, 6, 7, 8, 9] 最终结果:[1, 3, 4, 7, 8] */ } }
浙公网安备 33010602011771号