Giả sử có Iterable:
Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
Tạo Collection từ Iterable:
Collection<Integer> c = convertIterable(i);
Phương thức tùy chỉnh convertIterable():
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ụ hoàn chỉnh
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);
}
}
Kết quả
Collection (Iterable to Collection) = [50, 100, 150, 200, 250, 300, 500, 800, 1000]
Tối ưu: Nếu Iterable đã là List, cast trực tiếp tránh overhead tạo stream và collect mới. Nếu không, dùng StreamSupport như trên. Kết quả trả về là ArrayList (do Collectors.toList()).