0

Have a function that returns a Set<> I want to apply that function over another collection, create a flattened Set<> below is the code snippet with map with just variables renamed

 repository.findAll().stream().map(
                p -> forecastService.forecast(p, timeLineInYear, label)
        ).collect(Collectors.toSet());

ForecastService returns Set<Forecast> so the above statement returns Set<Set<Forecast>>

when I try turning the same statement with a flatMap

 repository.findAll().stream().flatMap(
                p -> forecastService.forecast(p, timeLineInYear, label)
        ).collect(Collectors.toSet());

I get an compilation error

no instance of type variable R exist so that Set<Forecast> conforms to Stream<? extends R>

Appreciate any help.

Somasundaram Sekar
  • 5,244
  • 6
  • 43
  • 85
  • 4
    The flatMap call is expecting a Stream, not a Set. Try `p -> forecastService.forecast(p, timeLineInYear, label).stream()`. – Stuart Marks Oct 31 '16 at 05:41

1 Answers1

0

You're making it wrong. The flatMap method converts your stream of stream -> stream. If you want to accumulate all elements in your Set of Set please consider to use stream.reduce().

fangdi
  • 121
  • 4
  • Ísn't this entirely opposite of what scala collection can do, where flatmap flattens your collection and reduce would reduce your collection to a single element. I can see what you have suggested with reduce may still work, but it is, I guess, is still a work around – Somasundaram Sekar Oct 31 '16 at 07:12