lambda使用Java流将对象映射到多个对象
我有一个关于Java流的问题。假设我有一个对象流,我想将每个对象映射到多个对象。比如说
IntStream.range(0, 10).map(x -> (x, x*x, -x)) //...
这里我想把每个值映射到同一个值,它的平方和带相反符号的同一个值。我找不到任何流操作来执行此操作。我想知道是否最好将每个对象x
映射到具有这些字段的自定义对象,或者将每个值收集到中间Map
(或任何数据结构)中
我认为在内存方面,创建自定义对象可能更好,但可能我错了
在设计正确性和代码清晰性方面,哪种解决方案更好?或者也许有更优雅的解决方案,我不知道
# 1 楼答案
可以使用
flatMap
为原始IntStream
的每个元素生成一个包含3个元素的IntStream
:输出:
# 2 楼答案
除了使用自定义类之外,例如:
然后跑
您可以使用apache commons InmmutableTriple来实现这一点。 例如:
maven repo:https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.6
文件:http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/ImmutableTriple.html