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

Stream ใน Java - คู่มือพื้นฐานและตัวอย่าง

Stream แสดง Sequence ของ Object จาก Source รองรับ Aggregate Operations ลักษณะสำคัญของ Stream:

  • Sequence of Elements - Stream ให้ชุด Elements แบบ Sequential คำนวณ On-Demand ไม่เก็บ Elements
  • Source - Stream รับ Input จาก Collections, Arrays, หรือ I/O Resources
  • Aggregate Operations - รองรับ filter, map, limit, reduce, find, match, ฯลฯ
  • Pipelining - Operations ส่วนใหญ่ Return Stream เอง เพื่อ Chain ได้ (Intermediate Operations) collect() เป็น Terminal Operation ปิดท้าย Pipeline
  • Automatic Iterations - Stream Iterate เองภายใน ไม่ต้อง Loop เองเหมือน Collections

ตัวอย่างที่ 1: Stream to Collection (TreeSet)

import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Demo {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("25", "10", "15", "20", "25");
        Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
        System.out.println("Collection = " + collection);
    }
}

ผลลัพธ์

Collection = [10, 15, 20, 25]

สังเกต: TreeSet กำจัด Duplicate และ เรียงลำดับอัตโนมัติ

ตัวอย่างที่ 2: นับจำนวน Elements ด้วย counting()

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

public class Demo {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("Kevin", "Jofra", "Tom", "Chris", "Liam");
        long count = stream.collect(Collectors.counting());
        System.out.println("Number of elements in the stream = " + count);
    }
}

ผลลัพธ์

Number of elements in the stream = 5

เพิ่มเติม: Stream API ใน Java 8+ เปลี่ยนแปลง Paradigm จาก External Iteration เป็น Internal Iteration โค้ดสะอาด อ่านง่าย และ Parallel ได้ง่ายด้วย parallelStream()