Java – use the stream API to create an object initialization loop

I have a set of constant values that can be used as a list Using these values, I must create a key - value pair object and add it to the list I want to use the stream API in Java 8 to achieve this The following is an example 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 achieved using flow reduction operations?

Solution

Chain intstream Iterate() uses intstream Limit() generates an infinite intstream 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());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>