Harshil Harshil - 19 days ago 5
Java Question

Stream's limit is not working for a Stream based on a char array

Why doesn't the below code limit the output to first three chars only?

String vowelOne = "aaebcd";

Stream
.of(vowelOne.toCharArray())
.limit(3)
.forEach(System.out::println);


Output:

aaebcd


I want the output to be:

aae

Answer

Stream.of(char[]) produces a Stream of a single char[] element (just like Arrays.asList() for a primitive array would produce a List of a single element), so limit(3) doesn't truncate the Stream, and you are printing the entire char[] (which you can also see from the fact that all the characters are printed in a single line even though you use println).

Try :

vowelOne.chars() // this returns an IntStream of the characters of the input String
        .limit(3)
        .forEach(i->System.out.println((char)i)); // without the casting to char, you'll
                                                  // get the numeric value of the first 3
                                                  // characters

Output :

a
a
e
Comments