假设以下是我们的Iterable-Iterable i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
现在,创建一个集合-Collection c = convertIterable(i);
上面,我们有一个自定义convertIterable()的转换方法。以下是方法-public static Collection convertIterable(Iterable iterable) {
if (iterable instanceof List) {
return (List) iterable;
}
return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
}
示例
以下是在Java中将Iterable转换为Collection的程序-import java.util.*;
import java.util.stream.*;
public class Demo {
public static Collection convertIterable(Iterable iterable) {
if (iterable instanceof List) {
return (List) iterable;
}
return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
}
public static void main(String[] args) {
Iterable i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
Collection c = convertIterable(i);
System.out.println("Collection (Iterable to Collection) = "+c);
}
}
输出结果Collection (Iterable to Collection) = [50, 100, 150, 200, 250, 300, 500, 800, 1000]