我想知道,是否有一些流操作可以像 ruby 中的 each_with_index
那样做。
其中 each_with_index
遍历值以及值的索引。
最佳答案
没有专门用于该目的的流操作。但您可以通过多种方式模仿该功能。
索引变量:以下方法适用于顺序流。
int[] index = { 0 };
stream.forEach(item -> System.out.printf("%s %d\n", item, index[0]++));
外部迭代:以下方法适用于并行流,只要原始集合支持随机访问。
List<String> tokens = ...;
IntStream.range(0, tokens.size()).forEach(
index -> System.out.printf("%s %d\n", tokens.get(index), index));
关于ruby - Java 8 相当于 ruby each_with_index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23347982/