用Java将Iterable转换为Collection
假设以下是我们的Iterable-
Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
现在,创建一个集合-
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]
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短