$show=/label

Java 8 Stream forEach With Index

SHARE:

A quick guide to print the index from java 8 foreach loop. Example programs on List and Array with any type objects using java 8 forEach index.

1. Overview

In this tutorial, We'll learn how to print the index when using java 8 forEach with streams.

In the realtime when working with list.stream().forEach() method, it does not allow to use the index variable which is declared outside lambda expression.  If we declare the variable inside lambda then it will be reset to initial value again. So, it is not possible and there are limitations while accessing the variables from inside lambda expressions

Let us explore the ways to get the indices when using forEach method on streams.

First, We'll show the example using Arrays and next on List of String objects. Getting the index value or number can be addressed with IntStream.range() method.

Java 8 forEach With Index (Indices)


2. Java forEach Array With Index


Follow the below steps to get the values with indices from Array of Strings.

Steps:

Step 1: Create a string array using {} with values inside.
Step 2: Get the length of array and store it inside a length int type variable
Step 3: Use IntStream.range() method with start index as 0 and end index as length of array. Next, Call forEach() method and it gets the index value from int stream. This index value starts from 0 value so we can get the value from string array using index as fruites[0].
Step 4: Print the value along with the index.

package com.javaprogramto.java8.foreach.index;

import java.util.stream.IntStream;

/**
 * Example program to run the forEach() loop with index in java 8 with an array of Strings.
 * 
 * @author JavaProgramTo.com
 *
 */

public class ForEachIndexArraysExample {

	public static void main(String[] args) {

		// Create an Array with Strings.
		String[] fruites = { "Mango", "Apple", "Orange", "Kiwi", "Avocado" };

		// getting length of an array.
		int length = fruites.length;

		// running foreach loop with index using IntStream.range() method with start and end index.
		IntStream.range(0, length)
				.forEach(index -> System.out.println("Value at Index : " + (index + 1) + " is " + fruites[index]));
	}
}
Output:
Value at Index : 1 is Mango
Value at Index : 2 is Apple
Value at Index : 3 is Orange
Value at Index : 4 is Kiwi
Value at Index : 5 is Avocado

We can observe the output that is having the index values.

And alos we can perform all normal stream operations such as map(), filter() on the IntStream.

Look the below line of code that gets only if the fruit name is having only letter "a" in it. But, it holds the actual index from the original array.
// with filter() method.
IntStream.range(0, length).filter(index -> fruites[index].contains("a"))
		.forEach(index -> System.out.println("Value at Index : " + (index + 1) + " is " + fruites[index]));


Output:
Value at Index : 1 is Mango
Value at Index : 3 is Orange
Value at Index : 5 is Avocado

3. Java forEach List With Index


Iterating the list using forEach with indices can be done in two ways. 

The first option is directly use the IntStream.range() method to get the index and call forEach() is get the values from list using index as list.get(index). This approach is similar to the foreach array with index.

Second approach is convert List to Map in such way that key should hold the index, value will be actual value from list. Finally, print the map using forEach(k, v).

3.1 Using IntStream.range()


Running forEach loop on top of IntStream.range() + filter() methods.

package com.javaprogramto.java8.foreach.index;

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

/**
 * Example program to run the forEach() loop with index in java 8 with an List
 * of Strings.
 * 
 * @author JavaProgramTo.com
 *
 */

public class ForEachIndexListExample {

	public static void main(String[] args) {

		// Create a List with Strings.
		List<String> players = Arrays.asList("Warner", "Ponting", "Akthar", "Sachin", "Gary Christian");

		// getting length of an List.
		int length = players.size();

		// running forEach loop with index using IntStream.range() method with start 0 and
		// end index as length
		IntStream.range(0, length).filter(index -> players.get(index).contains("a"))
				.forEach(index -> System.out.println("Value at Index : " + (index + 1) + " is " + players.get(index)));
	}
}

Output:
Value at Index : 1 is Warner
Value at Index : 3 is Akthar
Value at Index : 4 is Sachin
Value at Index : 5 is Gary Christian

3.2 Using Stream.collect() + Map + forEach()


Follow below steps to get the list with index. 

Step 1: Create a List with string of values.
Step 2: Convert the list to map using collect() method with Supplier and BiConsumer lambdas.
Step 3: Add the key as map.size() and value will be from stream.

Collect() Method Syntax:

collect() is a terminal operation.
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);
Example
package com.javaprogramto.java8.foreach.index;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Example program to run the forEach() loop with index in java 8 with an List
 * of Strings.
 * 
 * @author JavaProgramTo.com
 *
 */

public class ForEachIndexListMapExample {

	public static void main(String[] args) {

		// Create a List with Strings.
		List<String> players = Arrays.asList("Warner", "Ponting", "Akthar", "Sachin", "Gary Christian");


        HashMap<Integer, String> collect = players
                .stream()
                .collect(HashMap<Integer, String>::new,
                        (map, streamValue) -> map.put(map.size(), streamValue),
                        (map, map2) -> {
                        });

        collect.forEach((k, v) -> System.out.println(k + ":" + v));
	}
}

Output:
0:Warner
1:Ponting
2:Akthar
3:Sachin
4:Gary Christian

Here when the collect() is invoked, the first value is added to map before that map size will be 0. So, the index for first value will be 0. 
Next, when the second value is added to the map, index will be 1 because map has already one element from the previous step. So index is added as 1. 
These steps will be repeated till the last value in the stream. So for the last element index will be list.size()-1.

4. Conclusion


In this article, we've seen how to get the indices in java 8 Stream forEach() method using IntStream.range() and Stream.collect().forEach() method. This index will be considered as the position of the value in the collection or ArrayList.

Sometimes you may get out of bound error if you do not get the correct index.



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,17,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,29,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,93,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,35,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,14,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,111,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,105,Java Spark,1,java.lang,5,java.util. function,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,1,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,28,String,59,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Stream forEach With Index
Java 8 Stream forEach With Index
A quick guide to print the index from java 8 foreach loop. Example programs on List and Array with any type objects using java 8 forEach index.
https://1.bp.blogspot.com/-O1X4K8tFWUM/X8o80ve4-9I/AAAAAAAADH0/7yOs-GC6ubg46ZDXoO6Mz4tQWdXv8WWxACLcBGAsYHQ/w640-h480/Java%2B8%2BforEach%2BWith%2BIndex.png
https://1.bp.blogspot.com/-O1X4K8tFWUM/X8o80ve4-9I/AAAAAAAADH0/7yOs-GC6ubg46ZDXoO6Mz4tQWdXv8WWxACLcBGAsYHQ/s72-w640-c-h480/Java%2B8%2BforEach%2BWith%2BIndex.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/12/java-foreach-index.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/12/java-foreach-index.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content