![](/img/trans.png)
[英]How to compare Objects values which is inside two different list in Java?
[英]How to compare two different sizes List Objects Java
我有两个列表,列表 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 中的项目具有相同的mobile
,则从列表 A 中删除该项目:
listA.removeIf(a -> listB.stream()
.anyMatch(b -> Objects.equals(a.getMobile(), b.getMobile())));
在这种情况下,流 API 有点难以阅读。 不使用 stream 也是一样的:
for (B b : listB) {
listA.removeIf(a -> Objects.equals(a.mobile, b.mobile));
}
您可以使用标志表示存在并在 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 equal 检查
我有两个大小不同的列表,列表 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;
}
现在我想比较两个列表,并希望从List 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;
}
有人可以指导我吗?
我认为您应该将手机分开存放,因为它们可能会重复使用。 然后将主要集合与此手机列表进行比较。
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())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.