Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Stream trong Java

Stream đại diện cho chuỗi các đối tượng từ một source, hỗ trợ các aggregate operations. Đặc điểm của Stream:

  • Sequence of elements - Stream cung cấp tập hợp các element kiểu cụ thể theo trình tự. Stream lấy/tính toán element theo yêu cầu (lazy). Không lưu trữ element.
  • Source - Stream nhận Collections, Arrays, hoặc I/O resources làm input source.
  • Aggregate operations - Stream hỗ trợ filter, map, limit, reduce, find, match, v.v.
  • Pipelining - Hầu hết stream operations trả về stream chính nó để pipeline. Các operation này gọi là intermediate operations. collect() là terminal operation thường ở cuối pipeline.
  • Automatic iterations - Stream operations lặp nội bộ qua source elements, khác với Collections cần lặp explicit.

Ví dụ 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);
    }
}

Kết quả

Collection = [10, 15, 20, 25]

Lưu ý: Kết quả gốc trong bài có lỗi in ra [100, 130, 150, 20, 200, 50, 80] không khớp input. Kết quả đúng là [10, 15, 20, 25] do TreeSet loại trùng và sắp xếp.

Ví dụ 2: Đếm số element trong stream bằng 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("Số element trong stream = " + count);
    }
}

Kết quả

Số element trong stream = 5

Lưu ý: Stream chỉ dùng được một lần (consumed sau terminal operation). Cần tạo stream mới cho mỗi pipeline.