如何使用 Java 8 流将列表元素映射到它们的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28989841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to map elements of the list to their indices using Java 8 streams?
提问by Jaroslaw Pawlak
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 google collections:
有一个字符串列表,我需要构造一个有效配对的对象列表(string, its position in the list)
。目前我使用谷歌集合有这样的代码:
public Robots(List<String> names) {
ImmutableList.Builder<Robot> builder = ImmutableList.builder();
for (int i = 0; i < names.size(); i++) {
builder.add(new Robot(i, names.get(i)));
}
this.list = builder.build();
}
I would like to do this using Java 8 streams. If there was no index, I could just do:
我想使用 Java 8 流来做到这一点。如果没有索引,我可以这样做:
public Robots(List<String> names) {
this.list = names.stream()
.map(Robot::new) // no index here
.collect(collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
));
}
To get the index, I would have to do something like this:
要获得索引,我必须执行以下操作:
public Robots(List<String> names) {
AtomicInteger integer = new AtomicInteger(0);
this.list = names.stream()
.map(string -> new Robot(integer.getAndIncrement(), string))
.collect(collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
));
}
However, the documentation says that mapping function should be stateless, but the AtomicInteger
is effectively its state.
然而,文档说映射函数应该是无状态的,但AtomicInteger
实际上是它的状态。
Is there a way to map elements of the sequential stream to their positions in the stream?
有没有办法将顺序流的元素映射到它们在流中的位置?
采纳答案by Alexis C.
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
.
但是,根据列表的底层实现,它可能效率不高。你可以从IntStream
; 中获取一个迭代器。然后调用next()
的mapToObj
。
As an alternative, the proton-packlibrary defines the zipWithIndex
functionality for streams:
作为替代方案,proton-pack库定义了zipWithIndex
流的功能:
this.list = StreamUtils.zipWithIndex(names.stream())
.map(i -> new Robot(i.getIndex(), i.getValue()))
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
回答by assylias
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());