
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate Over a Stream with Indices in Java 8
To iterate over a Stream with Indices in Java 8, the code is as follows −
Example
import java.util.stream.IntStream; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; public class Demo{ public static void main(String[] args){ String[] my_array = { "T", "h", "i", "s", "s","a", "m", "p", "l", "e" }; AtomicInteger my_index = new AtomicInteger(); System.out.println("The elements in the string array are :"); Arrays.stream(my_array).map(str -> my_index.getAndIncrement() + " -> " + str).forEach(System.out::println); } }
Output
The elements in the string array are : 0 -> T 1 -> h 2 -> i 3 -> s 4 -> s 5 -> a 6 -> m 7 -> p 8 -> l 9 -> e
A class named Demo contains the main function. In this main function, an array of string type is declared and the AtomicInteger instance is created using the AtomicInteger class. The ‘getAndIncrement’ function is used to iterate over the elements of the string array and every element iterated over is printed on to the console.
Advertisements