[英]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.