Harshil Harshil - 1 year ago 61
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";




I want the output to be:


Answer Source

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
        .forEach(i->System.out.println((char)i)); // without the casting to char, you'll
                                                  // get the numeric value of the first 3
                                                  // characters

Output :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download