[英]Can we Merge these three nested for loops by using streams in java 8?
在嘗試使用Streams轉換以下代碼時,我最終出現了一些錯誤。 我無法通過使用流轉換它。 我無法使用Streams合並for循環
以下代碼是必須使用流更改的代碼。
for (Admin ah : subProducers) {
List<String> wns = ah.getAdminSitCodes().stream()
.map(new SitCodeMap()).map(Pair::getFirst)
.distinct().collect(Collectors.toList());
for (String wn : wns) {
for (String value : values) {
if (wn.equals(value)) {
admin.add(ah);
}
}
}
}
我試過如下
admin = subProducers.stream().map(sp-> sp.getAdminSitCodes().stream()
.map(new SitCodeMap())
.map(Pair::getFirst).distinct()).collect(Collectors.toList())
.stream()
.filter(wns->values.stream().anyMatch(v-
>wns.equals(v)))
.collect(Collectors.toList());
必須使用流將其轉換為列表
您可以使用Set
集合中的values
,然后將代碼完成為:
List<Admin> admin = subProducers.stream()
.filter(a -> a.getAdminSitCodes().stream()
.map(new SitCodeMap())
.map(Pair::getFirst) // assuming this is Stream<String>
.distinct()
.anyMatch(values::contains))
.collect(Collectors.toList());
你可能正在尋找stream的flatMap():
在flatMap之后,您將獲得在flatmap中創建的子流的所有元素的“扁平”流。
所以
subProducers.stream().flatMap(sp-> sp.getAdminSitCodes().stream())
生成所有adminSitCodes的流,而
subProducers.stream().map(sp-> sp.getAdminSitCodes().stream())
產生一股溪流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.