How to increment a value in Java Stream?

后端 未结 2 816
庸人自扰
庸人自扰 2020-12-18 04:11

I want to increment value of index with the each iteration by 1. Easily to be achieved in the for-loop. The variable image

2条回答
  •  无人及你
    2020-12-18 04:41

    Some kind of "zip" operation would be helpful here, though standard Stream API lacks it. Some third-party libraries extending Stream API provide it, including my free StreamEx library:

    IntStreamEx.ints() // get stream of numbers 0, 1, 2, ...
               .boxed() // box them
               .zipWith(StreamEx.ofValues(map)) // zip with map values
               .forKeyValue((index, item) -> image[index].setImage(item.getImage()));
    

    See zipWith documentation for more details. Note that your map should have meaningful order (like LinkedHashMap), otherwise this would be pretty useless...

提交回复
热议问题