英文:
number of items in the second list that aren't in the first list in java
问题
以下是您要翻译的内容:
"假设我的第一个列表是:
[{tenancyNumber:777,no:1}, {tenancyNumber:888,no:2}, {tenancyNumber:999,no:3}]
而我的第二个列表是
[{tenancyNumber:444,no:4}, {tenancyNumber:999,no:5}, {tenancyNumber:666,no:6}]
所以,如果我们按照名称在这两个列表中进行比较,第二个列表中有2个对象不在第一个列表中。如何在Java中找出这个差异?
这是我尝试过的代码:
final Long newAccounts = endDateData.stream()
.map(TenancyHistory::getTenancyNumber)
.filter(startDateData.stream().map(TenancyHistory::getTenancyNumber)::equals)
.count();
但这会引发错误
> [PredicateIncompatibleType] Predicate will always evaluate to false
> because types Stream<Long> and Long are incompatible"
希望这对您有所帮助。
英文:
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. How to find out this in 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<Long> and Long are incompatible
答案1
得分: 0
你可以首先创建一个包含租赁编号的查找 Set
,以在对第二个列表进行迭代时更轻松地进行过滤。
Set<Long> tenancies = startDateData.stream()
.map(TenancyHistory::getTenancyNumber)
.collect(Collectors.toSet());
现在你之前尝试的部分可以修正为:
final Long newAccounts = endDateData.stream()
.map(TenancyHistory::getTenancyNumber)
.filter(num -> !tenancies.contains(num)) // 这里
.count();
为了帮助你理解你遇到的错误消息,考虑以下代码:
(end/start)DateData.stream().map(TenancyHistory::getTenancyNumber)
这将返回一个 Stream<Long>
,现在你在 filter
阶段执行的操作是将一个 Stream<Long>
与另一个 Stream
中的租赁编号的 Long
值进行比较,如下:
startDateData.stream().map(TenancyHistory::getTenancyNumber)::equals
因此,错误消息指出这将始终评估为 false
。因此,你的结果值将始终为 0
。
英文:
You can first create a lookup Set
of tenancy numbers for easing in the filter while you iterate on the second list.
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
startDateData.stream().map(TenancyHistory::getTenancyNumber)::equals
and hence the error message read this would evaluate always to false
. Such that resulting value of your would always be 0
.
专注分享java语言的经验与见解,让所有开发者获益!
评论