Java8相当于ruby的each_with_index

Muh*_*edy 5 ruby java-8 java-stream

我想知道,如果有一些流操作可以像each_with_index红宝石那样做.

each_with_index在值迭代以及价值的指标.

nos*_*sid 5

没有专门为此目的的流操作.但您可以通过多种方式模仿功能.

索引变量:以下方法适用于顺序流.

int[] index = { 0 };
stream.forEach(item -> System.out.printf("%s %d\n", item, index[0]++));
Run Code Online (Sandbox Code Playgroud)

外部迭代:只要原始集合支持随机访问,以下方法适用于并行流.

List<String> tokens = ...;
IntStream.range(0, tokens.size()).forEach(
    index -> System.out.printf("%s %d\n", tokens.get(index), index));
Run Code Online (Sandbox Code Playgroud)