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
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));