java关于集合元素的比较,交集,并集,不重复元素的获取

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]
*/
}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值