Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

แปลง String เป็น List of Characters ใน Java

สมมติมี String:

String str = "Website!";

แปลง String เป็น List of Characters ด้วย Stream API:

List<Character> list = str.chars()
    .mapToObj(n -> (char) n)
    .collect(Collectors.toList());

ตัวอย่างโค้ดเต็ม

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);
    }
}

ผลลัพธ์

String = Website!
List of Characters = [W, e, b, s, i, t, e, !]

คำอธิบาย:

  • str.chars() คืน IntStream ของ Unicode Code Points
  • .mapToObj(n -> (char) n) แปลงแต่ละ int เป็น Character Object
  • .collect(Collectors.toList()) รวบรวมเป็น List

วิธีอื่น: ใช้ Loop แบบดั้งเดิม หรือ String.toCharArray() แล้ว Convert เป็น List