【发布时间】:2014-07-03 16:29:50
【问题描述】:
我正在查看IntStream 的文档,我看到了toArray 方法,但无法直接转到List<Integer>
肯定有办法将Stream 转换为List?
【问题讨论】:
-
@KarlRichter 另一个问题没有给你一个打字列表。此外,这个问题是四年前的问题,并且有 300 多个赞成票的答案。为什么我们现在要合并它?
我正在查看IntStream 的文档,我看到了toArray 方法,但无法直接转到List<Integer>
肯定有办法将Stream 转换为List?
【问题讨论】:
IntStream::boxedIntStream::boxed 将IntStream 转换为Stream<Integer>,然后您可以将collect 转换为List:
theIntStream.boxed().collect(Collectors.toList())
boxed 方法将IntStream 的int 原始值转换为Integer 对象流。单词"boxing" 命名int ⬌ Integer 转换过程。见Oracle Tutorial。
Java 16 带来了更短的 toList 方法。产生一个unmodifiable list。讨论here。
theIntStream.boxed().toList()
【讨论】:
toList 的静态导入,我认为这段代码会变得更短、更清晰、更漂亮。这是通过在文件的导入中放置以下内容来完成的:static import java.util.stream.Collectors.toList;。然后对方付费电话读取为.collect(toList())。
Collectors 类来完成的-> 收藏夹。之后,您只需在 Ctr+Space 处键入 toLi 即可让 IDE 填写 toList 并添加静态导入。
boxed() 部分
您可以使用Eclipse Collections 中提供的原始集合并避免装箱。
MutableIntList list =
IntStream.range(1, 5)
.collect(IntArrayList::new, MutableIntList::add, MutableIntList::addAll);
注意:我是 Eclipse Collections 的贡献者。
【讨论】:
MutableIntList list = IntLists.mutable.withAll(IntStream.range(1, 5))
您还可以在 Stream 上使用 mapToObj(),它接受一个 IntFunction 并返回一个对象值 Stream,该 Stream 包含将给定函数应用于该流的元素的结果。
List<Integer> intList = myIntStream.mapToObj(i->i).collect(Collectors.toList());
【讨论】:
boxed() 的委托。
查找以下使用 Java 8 查找每个 int 元素的平方的示例:-
IntStream ints = Arrays.stream(new int[] {1,2,3,4,5});
List<Integer> intsList = ints.map(x-> x*x)
.collect(ArrayList<Integer>::new, ArrayList::add, ArrayList::addAll);
【讨论】:
你可以使用collect方法:
IntStream.of(1, 2, 3).collect(ArrayList::new, List::add, List::addAll);
事实上,当您在对象流上调用 .collect(Collectors.toList()) 时,这几乎正是 Java 所做的:
public static <T> Collector<T, ?, List<T>> toList() {
return new Collectors.CollectorImpl(ArrayList::new, List::add, (var0, var1) -> {
var0.addAll(var1);
return var0;
}, CH_ID);
}
注意:第三个参数只有在你想运行并行收集时才需要;对于顺序收集,只提供前两个就足够了。
【讨论】: