简体   繁体   English

如何获取IntStream.map.forEach的索引?

[英]How to get indices of IntStream.map.forEach?

I have this line which prints the squares of the numbers 0 to 5: 我有这行打印数字0到5的平方:

IntStream.rangeClosed(0, 4).map(i ->i*i).forEach(System.out::println);

The output is 输出是

0
1
4
9
16

Is there a way to get the output like below? 有没有办法获得如下所示的输出?

0 :0
1 :1
2 :4
3 :9
4 :16

Once you map i to i*i you lose the original i . 一旦你map ii*i你失去原来的i

You can remove the map and do the calculation inside the forEach : 您可以删除map并在forEach进行计算:

IntStream.rangeClosed(0, 4).forEach(i -> System.out.println(i + ": " + i*i));

Or you could do it like this(mapping to a Pair of key/value): 或者您可以这样做(映射到一Pair键/值):

IntStream.rangeClosed(0, 4)
         .mapToObj(i -> new AbstractMap.SimpleEntry<>(i, i * i))
         .forEach(System.out::println);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM