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

查看:30
本文介绍了在 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.

[稍后必须调用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 检索列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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