String.chars()
Returns a stream of the character codes of a string.
Available since: Java 9
Syntax
public IntStream chars()Return value
IntStreamAn IntStream — a stream of int values, one per char.
Examples
Counting vowels:
void main() {
long vowels = "programming".chars()
.filter(c -> "aeiou".indexOf(c) != -1)
.count();
IO.println(vowels);
}Output:
3The stream elements are numbers; cast to char to get characters:
void main() {
"abc".chars().forEach(c -> IO.println(c + " " + (char) c));
}Output:
97 a
98 b
99 cNotes
The method is declared in the CharSequence interface since Java 8 and overridden in String in Java 9. For emoji and other characters outside the Basic Multilingual Plane use codePoints().
See also
- String.charAt() — Returns the character at the given index.
- String.toCharArray() — Copies the characters of a string into a new char[] array.
- Character.isDigit() — Checks whether a character is a digit. Related checks are isLetter(), isWhitespace(), isUpperCase().
Related recipes
In the tutorial
- String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.