I have a set of constant values that are available as a list. Using these values I have to create a key value pair object and this object has to be added to a list. I would like to achieve this using Stream API in JAVA 8. Below is the sample implementation using a for loop
for (int i=0; i<length; i+=2){
list.add(new sampleObject(constant[i],constant[i+1]);
}
Can this be implemented using Stream reduction operations?
Chain IntStream.iterate() that produces a infinite IntStream with IntStream.limit() to make it finite :
List<sampleObject> list =
IntStream.iterate(0, i -> i + 2)
.limit(Math.ceil(length / 2D))
.mapToObj(i -> new sampleObject(constant[i], constant[i+1]))
.collect(Collectors.toList());
Of course it can!
IntStream.iterate(0, i -> i < length, i -> i + 2)
.mapToObj(i -> new sampleObject(constant[i], constant[i+1]))
.collect(Collectors.toList());
I'm not sure off the top of my head, but constant may have to be final or effectively final for this to compile.
Note: I just realized, this overloaded iterate method was added in Java 9. Please see davidxxx's answer for a Java 8 solution!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With