List集合比较

最近感觉在删除数据库中间表时会对性能不好,所以就找了找List对比的方式。然后找到了~

经常操作集合数据,操作数据平常都是用循环来实现并集,交集,差集等运算,一直觉得不优雅,看到有更好的处理方式记录下,刚好工作也遇到。

并集:

List listA = new ArrayList();
listA.add(A);
listA.add(B);
ArrayList listB = new ArrayList();
listA.add(A);
listA.add(C);
listA.addAll(listB);
System.out.println(listA);

输出结果:[A, B, A, C]

交集:

listA.retainAll(listB);

输出结果:[A]

差集:
所有属于A但不属于B的元素组成集合,叫做A与B的差集,就是我有你没有的元素。

listA.removeAll(listB);

输出结果:[B]

无重复并集:

/*删除在listA出现的元素*/
listB.removeAll(listA);
/*把剩余listB元素加入到listA中*/
listA.addAll(listB);            

输出结果:[A, B, C]

List操作对象:
假设有这样一种业务场景,有两组List数据进行比较,其中根据对象中几个属性值进行比较,如果不同筛选出来做修改操作。

需要在实体类覆写equals和hashCode方法,这样可以上面列举操作集合方式来操作。(ps:eclipse快捷键ctrl+shift+s选择 Generate hashCode() and equals() 选项进行生成)

public class Student {
	private String id;
	private String name;
	private Integer age;
	private char sex;
	/**get set方法省略*/
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null) ? 0 : age.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + sex;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age == null) {
			if (other.age != null)
				return false;
		} else if (!age.equals(other.age))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (sex != other.sex)
			return false;
		return true;
	} 
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值