Java Stream:在列表中聚合所有在map()中收到的非空集合
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java Stream:在列表中聚合所有在map()中收到的非空集合,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2247字,纯文字阅读大概需要4分钟。
内容图文
我有包含字符串ID的集合idList.
函数getCollection为单个ID返回一个项集合(类型为MyType).此外,它可能会返回null.
所以对于来自idList的许多ID,我会得到一些空值和一些集合.
目标是将一组ID的getCollection的所有回复收集到最终List中.
我想象过像
List<MyType> reply = idList.stream().map(id -> getCollection(id))
.filter(p -> p != null).collect(Collectors.toList());
但它似乎不是一个有效的表达.如何使其有效?
此外,这个实现的性能如何?
解决方法:
你需要使用flatMap –
List<MyType> reply = idList.stream()
.map(id -> getCollection(id))
.filter(collection -> collection != null)
.flatMap(Collection::stream)
.collect(Collectors.toList());
如果您正在考虑地图和flatMap操作之间的差异,那么您可以咨询this excellent answer –
Both map and flatMap can be applied to a Stream and they both
return a Stream. The difference is that the map operation produces
one output value for each input value, whereas the flatMap operation
produces an arbitrary number (zero or more) values for each input
value.This is reflected in the arguments to each operation.
The map operation takes a Function, which is called for each value in
the input stream and produces one result value, which is sent to the
output stream.The flatMap operation takes a function that conceptually wants to
consume one value and produce an arbitrary number of values. However,
in Java, it’s cumbersome for a method to return an arbitrary number of
values, since methods can return only zero or one value. One could
imagine an API where the mapper function for flatMap takes a value and
returns an array or a List of values, which are then sent to the
output. Given that this is the streams library, a particularly apt way
to represent an arbitrary number of return values is for the mapper
function itself to return a stream! The values from the stream
returned by the mapper are drained from the stream and are passed to
the output stream. The “clumps” of values returned by each call to the
mapper function are not distinguished at all in the output stream,
thus the output is said to have been “flattened.”Typical use is for the mapper function of flatMap to return
Stream.empty() if it wants to send zero values, or something like
Stream.of(a, b, c) if it wants to return several values. But of course
any stream can be returned.
内容总结
以上是互联网集市为您收集整理的Java Stream:在列表中聚合所有在map()中收到的非空集合全部内容,希望文章能够帮你解决Java Stream:在列表中聚合所有在map()中收到的非空集合所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。