【发布时间】:2021-11-18 10:59:31
【问题描述】:
我想把我正在做的事情变成 lambda,在这种情况下,我会在另一个列表中滚动 (listRegistrationTypeWork),检查子列表 (getRegistrationTypeWorkAuthors) 是否为 != null,如果是也就是说,滚动它以查找 authorCoautor = 类型,并增加一个计数,以找出列表中有多少记录具有相同的类型。
public int qtyMaximumWorksByAuthorCoauthor(AuthorCoauthor type) {
int count = 0;
for (RegistrationTypeWork tab : listRegistrationTypeWork) {
if (CollectionUtils.isNotEmpty(tab.getRegistrationTypeWorkAuthors())) {
for (RegistrationTypeWorkAuthors author : tab.getRegistrationTypeWorkAuthors()) {
if (author.getAuthorCoauthor().equals(type))
count++;
}
}
}
return count;
}
【问题讨论】:
-
看看
stream()、flatMap()、filter()和count(),例如listRegistrationTypeWork.stream().flatMap(tab -> tab.getRegistrationTypeWorkAuthors().stream()).filter(author->author.getAuthorCoauthor().equals(type)).count()。使用CollectionUtils.isNotEmpty()意味着其中一些列表可能为空,因此您需要在此处添加一些检查,例如filter(tab->tab.getRegistrationTypeWorkAuthors() != null)在flatMap()之前。 -
到目前为止,您的尝试结果如何?你到底卡在哪里了?
-
Lambda 表达式:
(AuthorCoauthor type) -> { int count = 0; for(RegistrationTypeWork tab : listRegistrationTypeWork) { if(CollectionUtils.isNotEmpty(tab.getRegistrationTypeWorkAuthors())) { for(RegistrationTypeWorkAuthors author : tab.getRegistrationTypeWorkAuthors()) { if(author.getAuthorCoauthor().equals(type)) count++; } } } return count; }