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

Chuyển Iterable thành Stream trong Java

Giả sử có Iterable:

Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P");

Tạo Stream từ Iterable:

Stream<String> s = convertIterable(i);

Phương thức tùy chỉnh convertIterable() cho chuyển đổi:

public static <T> Stream<T> convertIterable(Iterable<T> iterable) {
    return StreamSupport.stream(iterable.spliterator(), false);
}

Ví dụ hoàn chỉnh

import java.util.*;
import java.util.stream.*;

public class Demo {
    public static <T> Stream<T> convertIterable(Iterable<T> iterable) {
        return StreamSupport.stream(iterable.spliterator(), false);
    }
    
    public static void main(String[] args) {
        Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P");
        Stream<String> s = convertIterable(i);
        System.out.println("Iterable to Stream: " + s.collect(Collectors.toList()));
    }
}

Kết quả

Iterable to Stream: [K, L, M, N, O, P]

Giải thích: Iterable không có phương thức stream() trực tiếp (chỉ Collection mới có). Cần dùng StreamSupport.stream(iterable.spliterator(), parallel). Tham số false = sequential stream, true = parallel stream.