In this article, we will take a look at 4 different methods to convert string to list of characters in java with examples.
1. Java 8 streams
A new method chars()
was added in String class in java 9.chars()
returns a stream of characters in integer format.
We can then use stream’s mapToObj()
method and convert each integer to corresponding character.mapToObj()
returns another stream which can be converted to a list using its toList()
method. Example,
String s = "codippa"; List<Character> list = s.chars(). mapToObj(c -> (char)c). toList(); System.out.println(list);
This will print
mapToObj()
is defined in Stream interface and is a default interface method.
2. toCharArray()
toCharArray()
method is defined in string class and it returns the characters contained in a string as an array.
This array can then be converted to a list by iterating using an enhanced for loop.
In every iteration, add the current loop element to a list as shown below
String s = "codippa"; char[] array = s.toCharArray(); List<Character> list = new ArrayList<>(); for (char c : array) { list.add(c); }
3. Java 9 codePoints()
This method is similar to the first method.
Instead of chars()
, we use codePoints()
method added in String class in java 9.
codePoints()
returns a stream of integers corresponding to the characters of string. Example,
String s = "codippa"; List<Character> list = s.codePoints(). mapToObj(c -> (char)c). toList();
4. Guava Lists class
Lists class in google guava library has a charactersOf()
method.
It accepts a string argument and returns a list with its characters. Example,
String s = "codippa"; List<Character> list = Lists.charactersOf(s);
That is all for this article on how to convert string to list of characters in java.
Hope it was useful.