Giả sử chuỗi:
String str = "Website!";
Chuyển chuỗi thành list ký tự:
List<Character> list = str.chars().mapToObj(n -> (char)n).collect(Collectors.toList());
Ví dụ hoàn chỉnh
import java.util.*;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args){
String str = "Website!";
System.out.println("String = " + str);
List<Character> list = str.chars().mapToObj(n -> (char)n).collect(Collectors.toList());
System.out.println("List of Characters = " + list);
}
}
Kết quả
String = Website! List of Characters = [W, e, b, s, i, t, e, !]
Giải thích: str.chars() trả về IntStream các code point Unicode. mapToObj(n -> (char)n) chuyển mỗi int thành Character object. collect(Collectors.toList()) gom vào List.
Cách khác: Dùng str.codePoints().mapToObj(c -> (char)c).collect(Collectors.toList()) để hỗ trợ full Unicode (surrogate pairs).