Java 流 - 如何将计数器 i 添加到流的第 n 个值

Java Stream - How to add counter i to nth value of the stream

如何在迭代流时将计数器值添加到每个第 n 个项目?

这是我最简单的代码:

Stream.of("a1","a2","a3")
    .map(x -> x + "counterValue")
    .findFirst()
    .ifPresent(System.out::println);

当我在每个 n 项中添加 "counterValue" 字符串时,我想要实现的是在每个第 n 个元素中添加第 i 个值。

当前程序给出的输出为 a1counterValue

我希望输出为 a10。 0 表示该元素的索引。

有人可以帮忙吗?

这是您要找的吗?

 List<String> input = Arrays.asList("one", "two");
 IntStream.range(0, input.size())
      .mapToObj(i -> input.get(i) + i)
      .collect(Collectors.toList()) // [one0, two1]

您可以通过使用 IntStream 来迭代使用索引,如下所示:

String[] arr = {"a1","a2","a3"};
int lentgh = arr.length;
IntStream.of(0, lentgh).
    mapToObj(((int i) -> i + arr[i])).findFirst().
     ifPresent(System.out::println);