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

前端 未结 2 710
甜味超标
甜味超标 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条回答
  • 2020-12-10 05:34

    You could do something like this:

    public Robots(List<String> names) {
        this.list = IntStream.range(0, names.size())
                             .mapToObj(i -> new Robot(i, names.get(i)))
                             .collect(collectingAndThen(toList(), Collections::unmodifiableList));
    }
    

    However it may not be as efficient depending on the underlying implementation of the list. You could grab an iterator from the IntStream; then calling next() in the mapToObj.

    As an alternative, the proton-pack library defines the zipWithIndex functionality for streams:

     this.list = StreamUtils.zipWithIndex(names.stream())
                            .map(i -> new Robot(i.getIndex(), i.getValue()))
                            .collect(collectingAndThen(toList(), Collections::unmodifiableList));
    
    0 讨论(0)
  • 2020-12-10 05:55

    The easiest way is to stream indices:

    List<Robot> robots = IntStream.range(0, names.size())
                                  .mapToObj(i -> new Robot(i, names.get(i))
                                  .collect(toList());
    
    0 讨论(0)
提交回复
热议问题