从Java 8中的java.util.stream.Stream检索列表 [英] Retrieving a List from a java.util.stream.Stream in Java 8

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

问题描述

我在玩Java 8 lambdas来轻松过滤集合。但我没有找到一个简明的方法来检索结果作为一个新的列表在同一语句。这是我迄今为止最简明的方法:

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.

[稍后编辑:调用顺序()是必要的原因是它的代码( forEach(targetLongList :: add) )如果流是并行的,则将是racy。即使这样,它也不会达到预期的效果,因为 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检索列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆