Retrieving a List from a java.util.stream.Stream in Java 8(从 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 中检索列表
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01