Groovy String.codePoints
Stream the Unicode code points in a string, combining valid surrogate pairs.
A simple example
String.codePoints
- Start with "A😀"
- Do this Count Unicode code points
- Result 2
Syntax
public IntStream codePoints()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyCount a name and reaction
A student response can combine ordinary letters, accents and emoji. Choose the unit being counted before applying a length limit, because code points and visible symbols do not always line up.
println "A😀".codePoints().count()
2
The emoji is one stream element.
Find a symbol beyond the BMP
A feedback or ticket label includes an emoji that needs a full Unicode code point. Inspect the symbol at the right boundary so the value sent to the next component represents the entire character.
println "ok😀".codePoints().anyMatch { cp -> cp > 65535 }
true
The stream exposes the full code point.
Read a parcel sorting code
The depot scans a parcel marked NC-17. This identifier uses only ASCII characters. Count all characters, including the separator, to check the scanner’s length field.
What to watch for
A grapheme may contain multiple code points. Emoji sequences and combining accents need special handling for cursor movement.