Skip to main content

Iterate ArrayList using Stream with Indices in Java 8

There are mainly 2 method to iterate ArrayList using Stream with indices in Java 8.

Example-

Input- arrayList { "t", "e", "c", "m", "e", "n", "t", "o", "r" }
Output- 

Index- 0, Value- t
Index- 1, Value- e
Index- 2, Value- c
Index- 3, Value- m
Index- 4, Value- e
Index- 5, Value- n
Index- 6, Value- t
Index- 7, Value- o
Index- 8, Value- r

Method 1- By using AtomicInteger

IterateUsingStream.java

package in.tecmentor;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class IterateUsingStream {

	public static void main(String[] args) {
		String[] array = { "t", "e", "c", "m", "e", "n", "t", "o", "r" };
		List<String> arrayList = Arrays.asList(array);
		AtomicInteger integer = new AtomicInteger();
		arrayList.stream().map(s -> "Index- " + integer.getAndIncrement() 
				+ ", Value- " + s).forEach(System.out::println);
	}
}

Output:

Index- 0, Value- t
Index- 1, Value- e
Index- 2, Value- c
Index- 3, Value- m
Index- 4, Value- e
Index- 5, Value- n
Index- 6, Value- t
Index- 7, Value- o
Index- 8, Value- r

Method 2- By using IntStream

IterateUsingStream2.java

package in.tecmentor;

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

public class IterateUsingStream2 {

	public static void main(String[] args) {
		String[] array = { "t", "e", "c", "m", "e", "n", "t", "o", "r" };
		List<String> arrayList = Arrays.asList(array);
		IntStream.range(0, arrayList.size())
				.mapToObj(index -> String.format("Index- %d, Value- %s",
						index, arrayList.get(index))).forEach(System.out::println);
	}
}

Output:

Index- 0, Value- t
Index- 1, Value- e
Index- 2, Value- c
Index- 3, Value- m
Index- 4, Value- e
Index- 5, Value- n
Index- 6, Value- t
Index- 7, Value- o
Index- 8, Value- r

Leave a Reply

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

Top