Anand Vaidya
Anand Vaidya

Reputation: 1461

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)

The error says 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. I realized the code issue lying within after I extracted a separate method from the lambda expression. The new answer lies below -

reportNames.stream()
            .map(reportName -> mapReportNameToFormParams(form, reportName))
            .flatMap(stream -> stream)
            .collect(Collectors.toList());

Upvotes: 1

Views: 313

Answers (1)

Naman
Naman

Reputation: 31868

The reason for that is the type returned from your map operation is Stream<T> and not 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 :

.flatMap(s -> s)

Upvotes: 1

Related Questions