Video in progress

Strong Middle 🌊 Streams and lambdas

What does "salom".chars().forEach(System.out::println) print, and what do you watch for when streaming text by characters?

It prints numbers, not letters: chars() returns an IntStream and gives each UTF-16 code unit as an int (115, 97, ...). To get a character, use mapToObj(c -> (char) c). Emoji and other characters outside the BMP consist of two chars, and for them you need codePoints().

📖 Answer

"salom".chars().forEach(System.out::println);
// 115 97 108 111 109

"salom".chars()
       .mapToObj(c -> String.valueOf((char) c))
       .forEach(System.out::println);
// s a l o m

Why IntStream: there is no CharStream, and Stream<Character> would box.

Now the hard part. In Java a char is a 16-bit UTF-16 code unit. Most characters fit in one char, but emoji and some other characters consist of two chars (a surrogate pair):

String s = "ok👍";
s.length();                    // 4, not 3
s.chars().count();             // 4
s.codePoints().count();        // 3

If you reverse or cut an emoji with chars(), half a surrogate remains and a ? or a broken character appears on screen.

The right way:

String reversed = s.codePoints()
        .mapToObj(Character::toString)          // Java 11+: int code point -> String
        .reduce("", (acc, ch) -> ch + acc);

This isn't complete either: some "characters" (flags, emoji with a modified skin tone) consist of several code points. To work with what the user sees (graphemes) you need BreakIterator.getCharacterInstance() or \X in a regex.

In practice: SMS length, nickname limits, truncating text in the UI: length() and chars() give the wrong answer for all of these.