Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a object initialization loop using Stream API

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?

like image 583
JavaiMaster Avatar asked Jul 26 '26 21:07

JavaiMaster


2 Answers

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());
like image 89
davidxxx Avatar answered Jul 28 '26 10:07

davidxxx


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!

like image 29
Jacob G. Avatar answered Jul 28 '26 11:07

Jacob G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!