简体   繁体   English

第二个列表中不在 java 中的第一个列表中的项目数

[英]number of items in the second list that aren't in the first list in java

Let's say my first list is:假设我的第一个列表是:

[{tenancyNumber:777,no:1}, {tenancyNumber:888,no:2}, {tenancyNumber:999,no:3}]

And my second List is我的第二个清单是

[{tenancyNumber:444,no:4}, {tenancyNumber:999,no:5}, {tenancyNumber:666,no:6}]

So, if we compare by name in the two lists there are 2 objects in the second list which are not in the first list.因此,如果我们在两个列表中按名称进行比较,则第二个列表中有 2 个不在第一个列表中的对象。 How to find out this in Java?如何在 Java 中找到这个?

This is what i tried:这是我尝试过的:

final Long newAccounts = endDateData.stream()
  .map(TenancyHistory::getTenancyNumber)
  .filter(startDateData.stream().map(TenancyHistory::getTenancyNumber)::equals)
  .count();

which is throwing an error这是抛出一个错误

[PredicateIncompatibleType] Predicate will always evaluate to false because types Stream and Long are incompatible [PredicateIncompatibleType] Predicate 将始终评估为 false,因为类型 Stream 和 Long 不兼容

You can first create a lookup Set of tenancy numbers for easing in the filter while you iterate on the second list.您可以首先在过滤器中创建一个查找租用号码Set ,以便在您迭代第二个列表时进行缓动。

Set<Long> tenancies = startDateData.stream()
                                   .map(TenancyHistory::getTenancyNumber)
                                   .collect(Collectors.toSet());

Now the attempt you made can be fixed as;现在您所做的尝试可以修复为;

final Long newAccounts = endDateData.stream()
                                    .map(TenancyHistory::getTenancyNumber)
                                    .filter(num -> !tenancies.contains(num)) // here
                                    .count();

To help you understand the error message that you were facing, consider the code为了帮助您了解您所面临的错误消息,请考虑代码

(end/start)DateData.stream().map(TenancyHistory::getTenancyNumber)

this would return a Stream<Long> , now what you ended up performing in your filter stage was to compare Stream<Long> to a Long value of tenancy number from another Stream as这将返回一个Stream<Long> ,现在您最终在filter阶段执行的是将Stream<Long>与另一个Stream的租户号的Long值进行比较

startDateData.stream().map(TenancyHistory::getTenancyNumber)::equals

and hence the error message read this would evaluate always to false .因此读取的错误消息将始终评估为false Such that resulting value of your would always be 0 .这样您的结果值将始终为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM