[英]Stream.map not converting into Stream of streams
reportNames.stream().map(reportName -> {
if(reportName.equalsIgnoreCase("品番別明細表")) {
List<String> parts = fetchParts(form.getFacility(), form.getYear(), form.getMonth());
return parts.stream().map(part ->
ExcelReportForm.builder().facility(form.getFacility())
.month(form.getMonth())
.year(form.getYear())
.partNumber(part)
.build()
);
} else {
return Collections.singletonList(ExcelReportForm.builder().facility(form.getFacility())
.month(form.getMonth())
.year(form.getYear())
.partNumber("")
.build());
}
}).flatMap(List::stream)
.collect(Collectors.toList());
Basically what I am trying to do is - I am trying to map a Stream<Object>
into Stream<Stream<Object>>
, but somehow lambda doesn't understand the underlying type, and throws error on .flatMap(List::stream)
基本上我想做的是 - 我试图将Stream<Object>
映射到Stream<Stream<Object>>
,但不知何故 lambda 不理解底层类型,并在.flatMap(List::stream)
The error says Non static method cannot be referenced from static context
.错误说Non static method cannot be referenced from static context
。
I am wondering what might be causing this.我想知道可能是什么原因造成的。 Can someone help me please?有人能帮助我吗?
UPDATE更新
I figured out the answer as pointed out by @nullpointer.我想出了@nullpointer 指出的答案。 I realized the code issue lying within after I extracted a separate method from the lambda expression.在我从 lambda 表达式中提取了一个单独的方法后,我意识到了代码问题。 The new answer lies below -新的答案在下面——
reportNames.stream()
.map(reportName -> mapReportNameToFormParams(form, reportName))
.flatMap(stream -> stream)
.collect(Collectors.toList());
The reason for that is the type returned from your map
operation is Stream<T>
and not List<T>
.原因是您的map
操作返回的类型是Stream<T>
而不是List<T>
。
Inferring the above from从以上推断
return parts.stream().map(part ->
ExcelReportForm.builder().facility(form.getFacility())
.month(form.getMonth())
.year(form.getYear())
.partNumber(part)
.build()
);
You can either collect the above to return a List<T>
and then proceed with the current code or instead apply the flatMap
to a Stream<Stream<T>>
you can rather use identity operation as :您可以收集上述内容以返回List<T>
然后继续当前代码,或者将flatMap
应用于Stream<Stream<T>>
您可以使用身份操作作为:
.flatMap(s -> s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.