简体   繁体   English

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

[英]Map object to multiple objects using Java stream

I have a question regarding Java streams. 我有一个关于Java流的问题。 Let's say I have a stream of Object and I'd like to map each of these objects to multiple objects. 假设我有一个Object流,我想将这些对象映射到多个对象。 For example something like 比如像

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

Here I want to map each value to the same value, its square and the same value with opposite sign. 在这里,我想将每个值映射到相同的值,它的正方形和具有相反符号的相同值。 I couldn't find any stream operation to do that. 我找不到任何流操作来做到这一点。 I was wondering if it would be better to map each object x to a custom object that has those fields, or maybe collect each value into intermediate Map (or any data structure). 我想知道将每个对象x映射到具有这些字段的自定义对象是否更好,或者可能将每个值收集到中间Map (或任何数据结构)中。

I think that in terms of memory it could be better to create a custom object, but maybe I'm wrong. 我认为就内存而言,创建自定义对象可能更好,但也许我错了。

In terms of design correctness and code clarity, which solution would be better? 在设计正确性和代码清晰度方面,哪种解决方案会更好? Or maybe there are more elegant solutions that I'm not aware of? 或者也许有更多我不了解的优雅解决方案?

You can use flatMap to generate an IntStream containing 3 elements for each of the elements of the original IntStream : 可以使用flatMap以产生IntStream包含用于每个原始的元件的3个元素IntStream

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

Output: 输出:

[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]

Besides using a custom class such as: 除了使用自定义类,例如:

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();}
}

and run 并运行

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

you could use apache commons InmmutableTriple to do so. 你可以使用apache commons InmmutableTriple这样做。 for example: 例如:

 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 maven repo: https//mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.6

documentation: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/ImmutableTriple.html 文档: 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