Streams from a CharSequence – Streams

Streams from a CharSequence

The CharSequence.chars() method creates a finite sequential ordered IntStream from a sequence of char values. The IntStream must be transformed to a Stream<Character> in order to handle the values as Characters. The IntStream.mapToObj() method can be used for this purpose, as shown at (2). A cast is necessary at (2) in order to convert an int value to a char value which is autoboxed in a Character. Conversion between streams is discussed in §16.5, p. 934.

Click here to view code image

String strSource = “banananana”;
IntStream iStream = strSource.chars();                   // (1)
iStream.forEach(i -> System.out.print(i + ” “));         // Prints ints.
// 98 97 110 97 110 97 110 97 110 97
strSource.chars()
         .mapToObj(i -> (char)i)                         // (2) Stream<Character>
         .forEach(System.out::print);                    // Prints chars.
// banananana

The following default method for building IntStreams from a sequence of char values (e.g., String and StringBuilder) is defined in the java.lang.CharSequence interface (§8.4, p. 444):

default IntStream chars()

Creates a finite sequential ordered stream of int values by zero-extending the char values in this sequence.

Streams from a String

The following method of the String class can be used to extract text lines from a string:

Stream<String> lines()

Returns a stream of lines extracted from this string, separated by line terminators.

In the code below, the string at (1) contains three text lines separated by the line terminator (\n). A stream of element type String is created using this string as the source at (2). Each line containing the word “mistakes” in this stream is printed at (3).

Click here to view code image

String inputLines = “Wise men learn from their mistakes.\n”                 // (1)
                  + “But wiser men learn from the mistakes of others.\n”
                  + “And fools just carry on.”;
Stream<String> lStream = inputLines.lines();                                // (2)
lStream.filter(l -> l.contains(“mistakes”)).forEach(System.out::println);   // (3)

Output from the code:

Click here to view code image

Wise men learn from their mistakes.
But wiser men learn from the mistakes of others.

Leave a Reply

Your email address will not be published. Required fields are marked *