How to map elements of the list to their indices using Java 8 streams?

前端 未结 2 720
甜味超标
甜味超标 2020-12-10 05:11

Having a list of strings, I need to construct a list of objects which are effectively pairs (string, its position in the list). Currently I have such code using

2条回答
  •  猫巷女王i
    2020-12-10 05:55

    The easiest way is to stream indices:

    List robots = IntStream.range(0, names.size())
                                  .mapToObj(i -> new Robot(i, names.get(i))
                                  .collect(toList());
    

提交回复
热议问题