Categories
collections java

iterate stream with index in Java8

In this post, we will learn to iterate stream with index in Java8

We will come across multiple streams tutorials, but in all the tutorials we never iterate with index numbers

In order to find the current index or other numeric operations index number will help us to get the position

In this tutorial, we are going to use IntStream  to get  index of the arraylist

Because there is no straight way to get index number in streams

Syntax
IntStream.range(start, end)
Example

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class IterateStreamWithIndex {

	public static void main(String[] args) {
		try {
			List<String> list = new ArrayList<String>();
			list.add("India");
			list.add("USA");
			list.add("Germany");

			IntStream.range(0, list.size())
					.forEach(x -> System.out.println("The index is " + x + " Value is " + list.get(x)));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
The index is 0 Value is India
The index is 1 Value is USA
The index is 2 Value is Germany
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/IterateStreamWithIndex.java

Related Articles

foreach in java8 using streams

sorting operations in java using streams

Leave a Reply

Your email address will not be published. Required fields are marked *