EN
Java - convert String to List<Character>
12
points
1. Using Java 8 stream
import java.util.List;
import java.util.stream.Collectors;
public class Example1 {
public static void main(String[] args) {
String text = "abc";
List<Character> list = text.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
System.out.println(list); // [a, b, c]
}
}
Output:
[a, b, c]
Note:
In Java there is more then 1 way to create stream of characters from String, take a look on this post:
2. Explicit iteration
import java.util.ArrayList;
import java.util.List;
public class Example2 {
public static void main(String[] args) {
String text = "abc";
List<Character> list = new ArrayList<>();
for (char c : text.toCharArray()) {
list.add(c);
}
System.out.println(list); // [a, b, c]
}
}
Output:
[a, b, c]