মান লিইজে নিচের আমাদের একটি Iterable −
Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
এখন, একটি Collection তৈরি করুন −
Collection<Integer> c = convertIterable(i);
উপরে, রূপান্তরের জন্য আমাদের একটি কাস্টম মেথড 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());
}
উদাহরণ
জাভাতে Iterable কে Collection-এ রূপান্তর করার প্রোগ্রাম −
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]