Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are char[] the only arrays not supported by Arrays.stream()?

Tags:

java

java-8

While going through the ways of converting primitive arrays to Streams, I found that char[] are not supported while other primitive array types are supported. Any particular reason to leave them out in the stream?

like image 201
ghostrider Avatar asked Feb 03 '20 10:02

ghostrider


People also ask

Can we apply streams on Array?

stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays. stream() won't work.

Can we use streams on Arrays in Java?

The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.


1 Answers

Of course, the answer is "because that's what the designers decided". There is no technical reason why CharStream could not exist.

If you want justification, you usually need to turn the the OpenJDK mailing list*. The JDK's documentation is not in the habit of justifying why anything is why it is.

Someone asked

Using IntStream to represent char/byte stream is a little inconvenient. Should we add CharStream and ByteStream as well?

The reply from Brian Goetz (Java Language Architect) says

Short answer: no.

It is not worth another 100K+ of JDK footprint each for these forms which are used almost never. And if we added those, someone would demand short, float, or boolean.

Put another way, if people insisted we had all the primitive specializations, we would have no primitive specializations. Which would be worse than the status quo.

Source

He also says the same elsewhere

If you want to deal with them as chars, you can downcast them to chars easily enough. Doesn't seem like an important enough use case to have a whole 'nother set of streams. (Same with Short, Byte, Float).

Source

TL;DR: Not worth the maintenance cost.


*In case you're curious, the google query I used was

site:http://mail.openjdk.java.net/ charstream 
like image 94
Michael Avatar answered Oct 19 '22 02:10

Michael