是否有一种简洁的方法来迭代流,同时访问流中的索引?
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 示例相比,这似乎相当令人失望
string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
var nameList = names.Where((c, index) => c.Length <= index + 1).ToList();
有没有更简洁的方法?
此外,zip 似乎已移动或被删除...
最佳答案
最简洁的方法是从索引流开始:
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”。
<小时/>当您习惯 for 循环时,一种看起来更熟悉的替代方法是使用可变对象(例如 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());
请注意,在并行流上使用后一种方法可能会中断,因为不一定“按顺序”处理项目。
关于java - 在 Java 8 中是否有一种简洁的方法来迭代带有索引的流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25062436/