Java 8嵌套流-转换循环的链接
我目前正在使用Java8特性 我有下面的一段代码,并尝试了多种使用Java 8嵌套流-转换循环的链接,java,for-loop,java-8,java-stream,Java,For Loop,Java 8,Java Stream,我目前正在使用Java8特性 我有下面的一段代码,并尝试了多种使用Streams的方法,但没有成功 for (CheckBox checkBox : checkBoxList) { for (String buttonFunction : buttonFunctionsList) { if (checkBox.getId().equals(buttonFunction)) { associatedCheckBoxList.add(checkBox);
Stream
s的方法,但没有成功
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);
});
});
谢谢 当您的目标是产生一些输出时,您应该更喜欢
collect
而不是forEach
:
List<CheckBox> associatedCheckBoxList =
checkBoxList.stream()
.filter(cb -> buttonFunctionsList.stream().anyMatch(bf -> cb.getId().equals(bf)))
.collect(Collectors.toList());
列出关联的复选框列表=
checkBoxList.stream()
.filter(cb->buttonFunctionsList.stream().anyMatch(bf->cb.getId().equals(bf)))
.collect(Collectors.toList());
Eran的答案可能很好;但是由于buttonFunctionList
可能是一个列表,因此它可能包含重复的元素,这意味着原始代码会多次将复选框添加到关联列表中
因此,这里有一种替代方法:将复选框添加到列表中的次数与在其他列表中出现该项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());
然后您可以在lambda中将其用作nCopies
的n
参数:
(int) frequencies.getOrDefault(cb.getId(), 0L)
不清楚
按钮功能列表
是否包含重复项:如果包含重复项,则此方法将忽略添加。@并且我认为将相同的复选框
多次添加到输出列表
是没有意义的。我可能错了。事实上,很可能没有复制品,或者如果有复制品的话,它们不是有意的。只是指出这是不一样的。
(int) frequencies.getOrDefault(cb.getId(), 0L)