从 Java 8 中的 java.util.stream.Stream 中检索列表

Retrieving a List from a java.util.stream.Stream in Java 8(从 Java 8 中的 java.util.stream.Stream 中检索列表)

本文介绍了从 Java 8 中的 java.util.stream.Stream 中检索列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Java 8 lambda 来轻松过滤集合.但是我没有找到一种简洁的方法来将结果检索为同一语句中的新列表.这是我迄今为止最简洁的方法:

I was playing around with Java 8 lambdas to easily filter collections. But I did not find a concise way to retrieve the result as a new list within the same statement. Here is my most concise approach so far:

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<>();
sourceLongList.stream().filter(l -> l > 100).forEach(targetLongList::add);

网上的例子没有回答我的问题,因为它们没有生成新的结果列表就停止了.必须有更简洁的方法.我本来希望 Stream 类具有 toList()toSet()、...

Examples on the net did not answer my question because they stop without generating a new result list. There must be a more concise way. I would have expected, that the Stream class has methods as toList(), toSet(), …

有没有办法让变量targetLongList直接由第三行赋值?

Is there a way that the variables targetLongList can be directly be assigned by the third line?

推荐答案

如果你的流保持顺序,你正在做的可能是最简单的方法——否则你将不得不在 forEach 之前调用sequential().

What you are doing may be the simplest way, provided your stream stays sequential—otherwise you will have to put a call to sequential() before forEach.

[稍后需要调用sequential() 的原因是,如果流是并行的,则代码(forEach(targetLongList::add)) 将是活泼的.即使这样,它也不会达到预期的效果,因为 forEach 是明确的非确定性的——即使在顺序流中,也不能保证元素处理的顺序.您必须使用 forEachOrdered 来确保正确排序.Stream API 设计者的意图是您将在这种情况下使用收集器,如下所示.]

[later edit: the reason the call to sequential() is necessary is that the code as it stands (forEach(targetLongList::add)) would be racy if the stream was parallel. Even then, it will not achieve the effect intended, as forEach is explicitly nondeterministic—even in a sequential stream the order of element processing is not guaranteed. You would have to use forEachOrdered to ensure correct ordering. The intention of the Stream API designers is that you will use collector in this situation, as below.]

另一种选择是

targetLongList = sourceLongList.stream()
    .filter(l -> l > 100)
    .collect(Collectors.toList());

这篇关于从 Java 8 中的 java.util.stream.Stream 中检索列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 Java 8 中的 java.util.stream.Stream 中检索列表

基础教程推荐