Giả sử sau đây là Lặp lại của chúng tôi -
Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P"); Bây giờ, hãy tạo Bộ sưu tập -
Stream<String> s = convertIterable(i);
Ở trên, chúng tôi có một phương thức tùy chỉnh convertIterable () để chuyển đổi. Sau đây là phương pháp -
public static <T> Stream<T> convertIterable(Iterable<T> iterable) {
return StreamSupport.stream(iterable.spliterator(), false);
} Ví dụ
Sau đây là chương trình chuyển đổi một Lặp lại có thể thành Luồng trong Java -
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()));
}
} Đầu ra
Iterable to Stream: [K, L, M, N, O, P]