Why isn't there IntStream.flatMapToObj()?

前端 未结 3 1529
情话喂你
情话喂你 2021-01-04 03:40

I\'m trying to do something like this:

Stream stream = IntStream.of(...)
        .flatMapToObj(i -> getStreamOfObjects(i));


<         


        
                      
相关标签:
3条回答
  • 2021-01-04 03:48

    Just write

     IntStream.of(...).mapToObj(i -> getStreamOfObjects(i)).flatMap(stream -> stream)
    
    0 讨论(0)
  • 2021-01-04 03:59

    Using a boxed stream would work if you don't mind the cost of boxing each int value.

    Stream<Object> stream = IntStream.of(...).boxed().flatMap(i -> getStreamOfObjects(i));
    
    0 讨论(0)
  • 2021-01-04 04:06

    Why was it was left out?

    The API provides reusable building blocks. The relevant building blocks here are IntStream, mapToObj, flatMap. From these you can achieve what you want: map an in stream to objects, and then get a flat map. Providing permutations of building blocks would not be practical, and harder to extend.

    What's a recommended workaround?

    As hinted earlier, use the available building blocks (mapToObj + flatMap):

    Stream<Object> stream = IntStream.of(...)
        .mapToObj(i -> Stream.of(...))
        .flatMap(...);
    
    0 讨论(0)
提交回复
热议问题