Junior — Middle
How can a string be transformed into a list of individual characters?
sobes.tech AI
Answer from AI
In Java, a string can be converted into a list of individual characters in several ways. One simple way is to use the toCharArray() method, which returns an array of characters, and then convert it into a list.
Example:
import java.util.*;
public class Main {
public static void main(String[] args) {
String str = "Example";
// Convert string to array of characters
char[] chars = str.toCharArray();
// Create a list of characters
List<Character> charList = new ArrayList<>();
for (char c : chars) {
charList.add(c);
}
System.out.println(charList);
}
}
You can also use Java 8 Stream API:
List<Character> charList = str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
This method is convenient and concise.