在 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...
推荐答案
最简洁的方法是从索引流开始:
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.
当您使用 for 循环时看起来更熟悉的一种替代方法是使用可变对象维护一个临时计数器,例如 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屋!