在 Java 中将 Iterable 转换为 Collection
javaobject oriented programmingprogramming更新于 2025/12/22 12:28:17
假设以下是我们的 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());
}
示例
以下是在 Java 中将 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]
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

