Java Reference ยท java.lang
Java String.chars() method
Reference for Java String.chars() and codePoints(): turn a string into an IntStream to count, filter and transform characters, and handle emoji correctly.
chars() returns an IntStream of the UTF-16 code units in a string. Each element is a char value widened to int, which is why you often see a cast back to char in stream pipelines. It lets you use filter, map, count and collect-style processing on text without writing a loop.
A sibling method, codePoints(), returns real Unicode code points instead. The two differ for characters outside the Basic Multilingual Plane (most emoji), which take two char values in Java.
long digits = "a1b22".chars().filter(Character::isDigit).count(); // 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public IntStream chars() // since 9 on String (declared by CharSequence since 8) public IntStream codePoints() // since 9 on String (declared by CharSequence since 8)
Returns: an IntStream in string order. chars() yields length() elements, codePoints() yields one element per code point, with each valid surrogate pair combined; an unpaired surrogate is passed through as is.
Throws: nothing. The stream is sequential, ordered, immutable in content and sized, so count() can answer without traversing in many cases.
Usage notes
- Elements are
int, notchar.mapToObj(c -> (char) c)gives aStream<Character>;mapToObj(c -> String.valueOf((char) c))gives aStream<String>. - Prefer
codePoints()for user text. Withchars(), an emoji counts as two elements and splitting or reversing it breaks the character apart. - Primitive stream operations:
sum(),max(),average(),filter(),map(),distinct(),sorted()andboxed()are available. There is nocollect(Collectors...)directly; callboxed()ormapToObj()first. - Rebuild a string with
mapToObjplusCollectors.joining(), or withStringBuilder::appendCodePointthroughcollect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append). - Performance. A plain
forloop overcharAt()is faster and allocates nothing; usechars()when clarity matters more than the last few nanoseconds. - The string is not modified. All results are new values.
- Character classification methods such as
Character.isLetter(int)haveintoverloads, so they work as method references on these streams.