How to iterate over a stream with indices in Java

1 Answer

0 votes
import java.util.stream.IntStream;

public class MyClass {
    public static void main(String args[]) {
        String[] arr = { "java", "c", "c++", "python", "c#"  };
 
        IntStream.range(0, arr.length)
                .mapToObj(index -> String.format("%d -> %s", index, arr[index]))
                .forEach(System.out::println);
    }
}




/*
run:

0 -> java
1 -> c
2 -> c++
3 -> python
4 -> c#

*/

 



answered Mar 16, 2023 by avibootz

Related questions

2 answers 162 views
162 views asked Sep 28, 2019 by avibootz
4 answers 172 views
172 views asked Nov 23, 2023 by avibootz
2 answers 202 views
1 answer 129 views
...