JShell เป็น interactive tool รับ simple statements, expressions แล้วประเมินและพิมพ์ผลทันที
Terminal Operation คือ stream operation ที่รับ stream as input และ ไม่คืนค่า output stream ตัวอย่าง terminal operation สามารถ apply กับ lambda expression ได้ผลลัพธ์เดียว (single primitive/object, หรือ single collection-of-objects) เมธอด reduce(), max(), และ min() เป็นตัวอย่าง terminal operations
ตัวอย่างใน JShell
jshell> IntStream.range(1, 11).reduce(0, (n1, n2) -> n1 + n2);
$1 ==> 55
jshell> List.of(23, 12, 34, 53).stream().max();
| Error:
| method max in interface java.util.stream.Stream cannot be applied to given types;
| required: java.util.Comparator super java.lang.Integer>
| found: no arguments
| List.of(23, 12, 34, 53).stream().max();
| ^----------------------------------^
jshell> List.of(23, 12, 34, 53).stream().max((n1, n2) -> Integer.compare(n1, n2));
$2 ==> Optional[53]
jshell> $2.isPresent()
$3 ==> true
jshell> List.of(23, 12, 34, 53).stream().max((n1, n2) -> Integer.compare(n1, n2)).get();
$4 ==> 53
jshell> List.of(23, 12, 34, 53).stream().filter(e -> e%2==1).forEach(e -> System.out.println(e))
23
53
jshell> List.of(23, 12, 34, 53).stream().filter(e -> e%2==1).collect(Collectors.toList());
$6 ==> [23, 53]
jshell> List.of(23, 12, 34, 53).stream().min((n1, n2) -> Integer.compare(n1, n2)).get();
$8 ==> 12
คำอธิบาย Terminal Operations
| Operation | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| forEach | ทำ action ทุก element | stream.forEach(System.out::println) |
| collect | รวบรวมเป็น collection | stream.collect(Collectors.toList()) |
| reduce | รวมเป็นค่าเดียว | stream.reduce(0, (a,b) -> a+b) |
| max/min | หาค่าสูงสุด/ต่ำสุด | stream.max(Comparator.naturalOrder()) |
| count | นับจำนวน elements | stream.count() |
| anyMatch/allMatch/noneMatch | ตรวจสอบเงื่อนไข | stream.anyMatch(x -> x > 10) |
| findFirst/findAny | หา element แรก/ใดๆ | stream.findFirst() |
| toArray | แปลงเป็น array | stream.toArray() |
ข้อสังเกตสำคัญ
- max()/min() ต้องการ Comparator - ไม่มี default สำหรับ object streams
- คืนค่า Optional - ต้องใช้
.get(),.orElse(), หรือ.ifPresent() - Terminal operation สามารถใช้ได้ครั้งเดียวต่อ stream - stream จะถูก consume
forEachไม่保证 order สำหรับ parallel streamscollect(Collectors.toList())
Primitive Stream Specializations
IntStream.range(1, 11).sum() // 55 - มี sum() built-in
IntStream.range(1, 11).average() // OptionalDouble[5.5]
IntStream.range(1, 11).max() // OptionalInt[11] - ไม่ต้อง Comparator
IntStream.range(1, 11).min() // OptionalInt[1]
DoubleStream.of(1.5, 2.5).sum() // 4.0