นากกายส่งกล่องค่าตามท่อสตรีมเข้ากล่องลิสต์ปิดผนึกสีอำพันบนโต๊ะมิ้นต์

Stream.toList(): ได้ลิสต์ immutable โดยไม่ต้อง collect

น้องกายEngineering

เคยเขียน .collect(Collectors.toList()) แล้วเผลอ add ต่อท้ายไหม ผมเคย จนย้ายมา Stream.toList()

ตามเอกสาร Stream เมธอด toList() คืน List ที่ unmodifiable — แก้ไม่ได้หลังสร้าง เหมาะเมื่อต้องการ snapshot ผลสตรีม

ต่างจาก Collectors.toList() ที่ได้ลิสต์แก้ได้ (ชนิดจริงขึ้นกับ implementation)

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    List<String> frozen = Stream.of("a", "b", "c").toList();
    if (frozen.size() != 3 || !"b".equals(frozen.get(1))) {
      throw new IllegalStateException("toList content");
    }
    boolean threw = false;
    try {
      frozen.add("d");
    } catch (UnsupportedOperationException ex) {
      threw = true;
    }
    if (!threw) {
      throw new IllegalStateException("expected unmodifiable");
    }

    List<String> mutable = Stream.of("a", "b").collect(Collectors.toList());
    mutable.add("c");
    if (mutable.size() != 3) {
      throw new IllegalStateException("mutable collect");
    }
    System.out.println("ok");
  }
}

Recap

  1. ใช้ toList() เมื่อต้องการลิสต์อ่านอย่างเดียว
  2. ใช้ Collectors.toList() / toCollection เมื่อต้องเติมต่อ
  3. toList() ไม่รับ null element — ตรวจก่อน
  4. อ่านเอกสารเวอร์ชัน JDK ที่ทีมใช้ให้ตรง