问题描述
我有两个列表,列表A和列表B具有不同的大小。列表A正在从文件中解析,列表B正在从数据库中获取数据。
class A{
private String id;
private String mobile;
}
class B{
private String id;
private String name;
private String address;
private String mobile;
private String pincode;
}
现在,我要同时比较列表和,并要从列表A 中删除与 ListB 具有相同手机号码的ID >。
尝试以下代码
private List<A> compareList(List<A> listA,List<B> listB){
List<A> temp = new ArrayList<>();
for(A a : listA){
for(B b : listB){
if(a.getId().equals(b.getId()) && !a.getMobile().equals(b.getMobile())){
temp.add(a);
}
}
}
return temp;
}
有人可以引导我吗?
解决方法
您的方法将创建一个新列表,而不是从现有列表中删除项目。假设您实际上要删除项目,这是使用Java 8流API的一种方法:如果项目与列表B中的项目具有相同的computed
,则从列表A中删除项目:
mobile
在这种情况下,流API有点难以阅读。不使用流的情况如下:
listA.removeIf(a -> listB.stream()
.anyMatch(b -> Objects.equals(a.getMobile(),b.getMobile())));
,
您可以使用标记来存在,如果不存在则添加temp,然后temp仅包含A中不存在于B中的那些元素
List<A> temp = new ArrayList<>();
for(A a : listA){
boolean isExist = false;
for(B b : listB){
if(a.getId().equals(b.getId()) && a.getMobile().equals(b.getMobile())){
isExist = true; // if exist in List of B
break;
}
}
if(!isExist){ // if not exist in B then add in list
temp.add(a);
}
}
注意:有问题的是,您说只比较手机号码,但是在代码中您也要比较id,如果不希望,请删除id等于检查
,-
当
temp
和id
相等时添加到mobile
。 -
最后从
temp
中删除所有listA
。 -
您不需要返回任何内容的方法,返回类型可以简单地为
void
。private void compareAndRemove(List<A> listA,List<B> listB) { List<A> temp = new ArrayList<>(); for (A a : listA) { for (B b : listB) { if (a.getId().equals(b.getId()) && a.getMobile().equals(b.getMobile())) { temp.add(a); } } } listA.removeAll(temp); }
我认为您应该将手机分开存放,因为它们可能会重复出现。然后将主要收藏夹与此手机列表进行比较。
private static List<A> compareList(List<A> listA,List<B> listB) {
List<String> mobiles = listB.stream()
.map(B::getMobile)
.distinct()
.collect(Collectors.toList());
return listA.stream()
.filter(entity -> !mobiles.contains(entity.getMobile()))
.collect(Collectors.toList());
}
,
创建新的过滤列表
如果条件不匹配,则收集新列表中的所有元素
List<A> filteredList =
aList.stream()
.filter(Predicate.not(a -> bList.stream().anyMatch(b -> a.getId().equals(b.getId()) && a.getMobile().equals(b.getMobile()))))
.collect(Collectors.toList());
用于就地替换
aList.removeIf(a -> bList.stream().anyMatch(b -> a.getId().equals(b.getId()) && a.getMobile().equals(b.getMobile())));