สมมติมี Iterable ดังนี้:
Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
สร้าง Collection จาก Iterable ด้วย Custom Method 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());
}
ตัวอย่างโค้ดเต็ม
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);
}
}
ผลลัพธ์
Collection (Iterable to Collection) = [50, 100, 150, 200, 250, 300, 500, 800, 1000]
เหตุผลที่ Check instanceof List: หาก Iterable เป็น List อยู่แล้ว ให้ Cast ตรงๆ ประหยัด Overhead ของ Stream/Spliterator