[英]Java 8 nested streams - convert chained for loops
我目前正在使用Java 8功能。
我有以下代码,并尝试了多种使用Stream
的方法,但没有成功。
for (CheckBox checkBox : checkBoxList) {
for (String buttonFunction : buttonFunctionsList) {
if (checkBox.getId().equals(buttonFunction)) {
associatedCheckBoxList.add(checkBox);
}
}
}
我尝试了以下操作,但不确定是否正确:
checkBoxList.forEach(checkBox -> {
buttonFunctionsList.forEach(buttonFunction -> {
if (checkBox.getId().equals(buttonFunction))
associatedCheckBoxList.add(checkBox);
});
});
谢谢!
伊兰的答案可能还不错。 但是由于buttonFunctionList
是(大概是)一个List,所以它可能包含重复的元素,这意味着原始代码会将复选框多次添加到关联的列表中。
因此,这是另一种方法:将复选框添加到列表的次数与另一个列表中该项目ID的出现次数相同。
这样,您可以将内部循环编写为:
int n = Collections.frequency(buttonFunctionList, checkBox.getId();
associatedCheckboxList.addAll(Collections.nCopies(checkBox, n);
因此,您可以这样写:
List<CheckBox> associatedCheckBoxList =
checkBoxList.flatMap(cb -> nCopies(cb, frequency(buttonFunctionList, cb.getId())).stream())
.collect(toList());
(为简洁起见,请使用静态导入)
如果checkBoxList
或buttonFunctionList
很大,则可能需要考虑一次计算频率:
Map<String, Long> frequencies = buttonFunctionList.stream().collect(groupingBy(k -> k, counting());
然后,您可以在lambda中将其用作nCopies
的n
参数:
(int) frequencies.getOrDefault(cb.getId(), 0L)
当您的目标是产生一些输出Collection
时,您应该首选collect
forEach
:
List<CheckBox> associatedCheckBoxList =
checkBoxList.stream()
.filter(cb -> buttonFunctionsList.stream().anyMatch(bf -> cb.getId().equals(bf)))
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.