繁体   English   中英

使用Java流将对象映射到多个对象

[英]Map object to multiple objects using Java stream

我有一个关于Java流的问题。 假设我有一个Object流,我想将这些对象映射到多个对象。 比如像

IntStream.range(0, 10).map(x -> (x, x*x, -x)) //...

在这里,我想将每个值映射到相同的值,它的正方形和具有相反符号的相同值。 我找不到任何流操作来做到这一点。 我想知道将每个对象x映射到具有这些字段的自定义对象是否更好,或者可能将每个值收集到中间Map (或任何数据结构)中。

我认为就内存而言,创建自定义对象可能更好,但也许我错了。

在设计正确性和代码清晰度方面,哪种解决方案会更好? 或者也许有更多我不了解的优雅解决方案?

可以使用flatMap以产生IntStream包含用于每个原始的元件的3个元素IntStream

System.out.println(Arrays.toString(IntStream.range(0, 10)
                                            .flatMap(x -> IntStream.of(x, x*x, -x))
                                            .toArray()));

输出:

[0, 0, 0, 1, 1, -1, 2, 4, -2, 3, 9, -3, 4, 16, -4, 5, 25, -5, 6, 36, -6, 7, 49, -7, 8, 64, -8, 9, 81, -9]

除了使用自定义类,例如:

class Triple{
private Integer value;
public Triple(Integer value){
 this.value = value;
}

public Integer getValue(){return this.value;}
public Integer getSquare(){return this.value*this.value;}
public Integer getOpposite(){return this.value*-1;}
public String toString() {return getValue()+", "+this.getSquare()+", "+this.getOpposite();}
}

并运行

IntStream.range(0, 10)
         .mapToObj(x -> new Triple(x))
         .forEach(System.out::println);

你可以使用apache commons InmmutableTriple这样做。 例如:

 IntStream.range(0, 10)
.mapToObj(x -> ImmutableTriple.of(x,x*x,x*-1))
.forEach(System.out::println);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM