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

前端 未结 2 709
甜味超标
甜味超标 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 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));
    

提交回复
热议问题