Java 8 嵌套流 - 转换链式 for 循环

我目前正在玩 Java 8 features 。


我有以下一段代码,并尝试了多种使用Streams 的方法,但没有成功。


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);

     });

     });


噜噜哒
浏览 152回答 2
2回答

明月笑刀无情

Eran 的回答可能不错;但由于buttonFunctionList是(大概)一个列表,它有可能包含重复的元素,这意味着原始代码会多次将复选框添加到关联列表中。所以这是另一种方法:您将复选框添加到列表中的次数与该项目的 id 在另一个列表中出现的次数相同。因此,您可以将内部循环编写为:int n = Collections.frequency(buttonFunctionList, checkBox.getId();associatedCheckboxList.addAll(Collections.nCopies(checkBox, n);因此,您可以将其写为:List<CheckBox> associatedCheckBoxList =&nbsp; &nbsp; checkBoxList.flatMap(cb -> nCopies(cb, frequency(buttonFunctionList, cb.getId())).stream())&nbsp; &nbsp; &nbsp; &nbsp; .collect(toList());(为简洁起见,使用静态导入)如果任一checkBoxList或者buttonFunctionList是大的,你可能要考虑计算频率一次:Map<String, Long> frequencies = buttonFunctionList.stream().collect(groupingBy(k -> k, counting());然后你可以在 lambda 中使用 this 作为n参数nCopies:(int) frequencies.getOrDefault(cb.getId(), 0L)

精慕HU

你应该更喜欢collect在forEach当你的目标是要产生一些输出Collection:List<CheckBox>&nbsp;associatedCheckBoxList&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;checkBoxList.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(cb&nbsp;->&nbsp;buttonFunctionsList.stream().anyMatch(bf&nbsp;->&nbsp;cb.getId().equals(bf))) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java