需求:我现在有两个list<User>,一个是全集所有元素集合A,一个是通过条件筛选出来的元素集合B。我需要把A中与B中的相同的对象,添加一个boolean字段赋值为true,其余为false。
思路:首先在实体类中添加一个字段
@Column
private boolean tf;
然后重写equals和hashCode方法
@Override
public boolean equals(Object obj){
UserEntity ce = (UserEntity)obj;
return classid.equals(ce.classid)&& classname.equals(ce.classname);
}
@Override
public int hashCode(){
String in = classid +classname;
return in.hashCode();
}
这里说明一下
return classid.equals(ce.classid)&& classname.equals(ce.classname);
是根据我想要比较对象的字段来定的,具体一点,这里就是我想要去除classid和classname相同的对象。
接着到Controller中
List<UserEntity> B = classidandNameRepository.findAll(uuidReturn.getUserid());
List<UserEntity> A = classidandNameRepository.findAllClass(uuidReturn.getSchoolid());
List<UserEntity> out = new ArrayList<>();
A.removeAll(B);//除去A中所有与B相同的对象
out.addAll(A);//把A加入out
for (UserEntity aa: B){
aa.setTf(true);//遍历B把boolean全部赋为true
}
out.addAll(B);//再把B加入out
整体流程:通过给实体类加了一个boolean字段,所有对象的boolean都变成了false,然后去除B中与A相同的对象,接着把A中的对象都赋上true,然后再加入到out中。