您可以执行以下操作:
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));}但是,根据列表的基础实现,它可能效率不高。您可以从中获取一个迭代器
IntStream;然后调用
next()的
mapToObj。
作为替代方案,质子包装库定义了
zipWithIndex流的功能:
this.list = StreamUtils.zipWithIndex(names.stream()) .map(i -> new Robot(i.getIndex(), i.getValue())) .collect(collectingAndThen(toList(), Collections::unmodifiableList));



