Why can't Stream.flatMap accept a collection?

后端 未结 1 1911
旧时难觅i
旧时难觅i 2020-12-19 04:54

Given the following as an example of data classes:

class Country {

    List regions = new ArrayList<>();

    List getRegi         


        
相关标签:
1条回答
  • 2020-12-19 05:17

    A technical reason, which is not ideal but could be why this wasn't done. You can't overload on a generic type in Java.

    They need to support

     Stream.flatMap(Function<Object, Stream<X>> function)
    

    which means they can't overload it with

     Stream.flatMap(Function<Object, Collection<X>> function)
    

    as these two methods have the same signature after erasure.

    They could add a method

     Stream.flatMapCollection(Function<Object, Collection<X>> function)
    

    or

     Stream.flatMapIterable(Function<Object, Iterable<X>> function)
    
     Stream.flatMapI(Function<Object, Iterable<X>> function)
    

    but it wouldn't be pretty.

    0 讨论(0)
提交回复
热议问题