经常操作集合数据,操作数据平常都是用循环来实现并集,交集,差集等运算,一直觉得不优雅,看到有更好的处理方式记录下,刚好工作也遇到。
并集:
List<String> listA = new ArrayList<String>();
listA.add("A");
listA.add("B");
ArrayList<String> listB = new ArrayList<String>();
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;
}
}