Map object for multiple objects using Java stream

I have a question about Java threads. Say I have an Object stream, and I would like to map each of these objects to multiple objects. For example, something like

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

Here I want to match each value with the same value, its square and the same value with the opposite sign. I could not find any stream operation to do this. I was wondering if it would be better to map each object xto a user object that has these fields, or maybe put each value into an intermediate Map(or any data structure).

I think it's better to create a custom object from a memory point of view, but maybe I'm wrong.

As for the correct design and code clarity, which solution would be better? Or maybe there are more elegant solutions that I don’t know about?

+4
source share
2 answers

In addition to using a custom class , for example:

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 can use apache commons InmmutableTriple for this. eg:

 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

0
source

You can use flatMapto create IntStreamcontaining 3 elements for each of the elements of the original IntStream:

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

Conclusion:

[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]
+2
source

Source: https://habr.com/ru/post/1694947/


All Articles