String.chars() and String.codePoints() Streams
You'll learn how to convert a String into a stream of its individual characters for functional processing.
The Core Idea
Java Strings provide two methods that generate IntStream instances representing their characters: chars() and codePoints(). Both let you process text at the character level using the declarative Stream API instead of traditional loops.
The key difference: chars() returns the 16-bit UTF-16 code units (what Java's char primitive uses), while codePoints() returns the actual Unicode code points. For most common characters these are identical, but for emoji and rare characters outside the Basic Multilingual Plane, codePoints() correctly handles multi-char sequences.
Why IntStream Instead of Stream<Character>?
Characters are represented as integers in Unicode. Returning IntStream avoids the overhead of boxing each character into a Character object, making processing more efficient.
Basic Usage
String text = "Hello";
// Get stream of char values (as ints)
text.chars()
.forEach(c -> System.out.print((char) c + " "));
// Output: H e l l o
// Get stream of Unicode code points
text.codePoints()
.forEach(cp -> System.out.print(Character.toString(cp) + " "));
// Output: H e l l o
Common Operations
String word = "Stream";
// Count vowels
long vowelCount = word.chars()
.filter(c -> "AEIOUaeiou".indexOf(c) >= 0)
.count();
// Convert to uppercase using map
String upper = word.chars()
.map(Character::toUpperCase)
.collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append)
.toString();
Key Takeaway: Use chars() and codePoints() to convert Strings into IntStream for functional character-level processing; prefer codePoints() when handling full Unicode correctness matters.