Why has Java 8 no "myArray.stream()" function?


I wonder why Java 8 does not include support to use streams on arrays the same way it does on collections. You can write

    Collection<String> myCollection = new ArrayList<String>();
    Stream<String> stream = myCollection.stream();

but you cannot write:

    String[] myArray = new String[] {};
    Stream<String> stream = myArray.stream();

I am aware of the utility method Arrays.stream, so this is can be used instead:

    Stream<String> stream = Arrays.stream(myArray);

But it leaves me wondering why this clumsy call of a static utility method is required in a context where lambda expression allow to simply code so much. I am aware of the significant difference between the (object/interface based) world of Collection and the more "native" world of array.

Who can elaborate on this?

Show source
| java   | arrays   | lambda   2017-01-02 13:01 3 Answers

Answers to Why has Java 8 no &quot;myArray.stream()&quot; function? ( 3 )

  1. 2017-01-02 13:01

    Something very close to your suggestion was discussed but the feature request was declined:

    What you are suggesting is a not-small language feature to provide a small bit of sugar to something you can already easily do with the libraries. So, while we've considered the possibility of adding a mechanism for injecting methods into arrays, the ease of just wrapping the array in this manner suggests we are probably better off spending our complexity budget elsewhere, unless we can derive some other larger benefit from this.

  2. 2017-01-02 13:01

    In order to add methods to arrays, the language, not the library, needs to be changed. Unlike "regular" objects with members defined in class files, arrays have their members defined directly in the language specification.

    This means that adding myArray.stream() method would require changing the language specification, and adding support to the compiler. This approach is a lot more complex than adding Arrays.stream(myArray), which can be implemented entirely within Java class library with very little effort.

  3. 2017-01-02 13:01

    The arrays are specified fully in the Java Language Specfication. Where as all Collection classes are only part of the API. And as you might imagine changes to the specification are more expensive to make than changes to the API.

    What you suggest would not just mean an addition to the specification, but also that the class Stream is known in the language specification. While this is technically possible (see for instance Class and Object), this is not very common. Note even the Collection classes are part of the language specification.

Leave a reply to - Why has Java 8 no "myArray.stream()" function?

◀ Go back