是否有一种简洁的方法来迭代Java 8中的索引流? [英] Is there a concise way to iterate over a stream with indices in Java 8?
问题描述
是否有一种简洁的方法来迭代流,同时可以访问流中的索引?
Is there a concise way to iterate over a stream whilst having access to the index in the stream?
String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
List<String> nameList;
Stream<Integer> indices = intRange(1, names.length).boxed();
nameList = zip(indices, stream(names), SimpleEntry::new)
.filter(e -> e.getValue().length() <= e.getKey())
.map(Entry::getValue)
.collect(toList());
与给出的LINQ示例相比,这似乎相当令人失望
which seems rather disappointing compared to the LINQ example given there
string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
var nameList = names.Where((c, index) => c.Length <= index + 1).ToList();
有更简洁的方法吗?
此外,似乎拉链已被移动或被移除......
Further it seems the zip has either moved or been removed...
推荐答案
最干净的方法是从一个流开始index:
The cleanest way is to start from a stream of indices:
String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
IntStream.range(0, names.length)
.filter(i -> names[i].length() <= i)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
结果列表仅包含Erik。
The resulting list contains "Erik" only.
当您习惯于循环时,一种看起来更熟悉的替代方法是使用可变对象维护一个临时计数器,例如 AtomicInteger
:
One alternative which looks more familiar when you are used to for loops would be to maintain an ad hoc counter using a mutable object, for example an AtomicInteger
:
String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
AtomicInteger index = new AtomicInteger();
List<String> list = Arrays.stream(names)
.filter(n -> n.length() <= index.incrementAndGet())
.collect(Collectors.toList());
请注意,在并行流上使用后一种方法的 可能会作为项目中断不会按顺序处理 。
Note that using the latter method on a parallel stream could break as the items would not necesarily be processed "in order".
这篇关于是否有一种简洁的方法来迭代Java 8中的索引流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!