通过迭代器用next方法,根据对象属性去掉list中对象,易忽略的点

如下:根据对象的属性,去除不需要对象,发现
1.报错,空指针
2.去重不准确
//去不需要重复数据
String[] type = {"02居家观察","03健康监测","04不承认但已签承诺书做核酸"};
Iterator<FactRoutine> it = factRoutineList.iterator();
while(it.hasNext()){
String str = (String)it.next().getIsRepeat();
it.next().getControlType();
String controlType = (String)it.next().getControlType();
//去重复数据
if("是".equals(str)){
it.remove();
continue;
}
//去类型不符数据
if (controlType.equals(type[0])||controlType.equals(type[1])||controlType.equals(type[2])){
continue;
}else {
it.remove();
}

}

通过了解.next调用原理,发现其中两次调用了.next,导致
1.执行一遍,跳转两个数据;
2.两次判断的属性并非来自同一个对象

 

需要多个条件去重,可以用list自带的removeIf方法解决,如下:

//去不需要重复数据
String[] type = {"02居家观察","03健康监测","04不承认但已签承诺书做核酸"};
// Iterator<FactRoutine> it = factRoutineList.iterator();
factRoutineList.removeIf(it->{
String str = (String)it.getIsRepeat();
String controlType = (String)it.getControlType();
//去重复数据
boolean flag1 = "是".equals(str);
//去类型不符数据
boolean flag2 = controlType.equals(type[0])||controlType.equals(type[1])||controlType.equals(type[2]);
boolean flag = flag1||!flag2;
return flag;
});

至此问题完美解决

posted @ 2022-06-01 10:40  洛枫雨落  阅读(288)  评论(1)    收藏  举报