Giả sử sau đây là Lặp lại của chúng tôi -
Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
Bây giờ, hãy tạo Bộ sưu tập -
Collection<Integer> c = 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> Collection<T> convertIterable(Iterable<T> iterable) {
if (iterable instanceof List) {
return (List<T>) iterable;
}
return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
} Ví dụ
Sau đây là chương trình để chuyển đổi một Lặp lại thành Bộ sưu tập trong Java -
import java.util.*;
import java.util.stream.*;
public class Demo {
public static <T> Collection<T> convertIterable(Iterable<T> iterable) {
if (iterable instanceof List) {
return (List<T>) iterable;
}
return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
}
public static void main(String[] args) {
Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
Collection<Integer> c = convertIterable(i);
System.out.println("Collection (Iterable to Collection) = "+c);
}
} Đầu ra
Collection (Iterable to Collection) = [50, 100, 150, 200, 250, 300, 500, 800, 1000]