从 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());
相关文章