$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 real-time 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 the 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 the List of String objects. Getting the index value or number can be addressed with IntStream.range() method.

Java 8 Stream forEach With Index




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 the array and store it inside a variable named length which is int type.
Step 3: Use IntStream.range() method with start index as 0 and end index as length of array. Next, the Call forEach() method and gets the index value from the int stream. This index value starts from 0 value so we can get the value from the string array using the 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 also we can perform all normal stream operations such as map(), filter() on the IntStream.

Look at the below line of code that gets only if the fruit name is having the only the 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 an index.

The second approach is converting List to Map in such a way that the key should hold the index, the value will be the 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 the below steps to get the list with the index. 

Step 1: Create a List with a string of values.
Step 2: Convert the list to map using the collect() method with Supplier and BiConsumer lambdas.
Step 3: Add the key as map.size() and value will be from the 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 the first value will be 0. 
Next, when the second value is added to the map, the index will be 1 because the map has already one element from the previous step. So the 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,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,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,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,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://blogger.googleusercontent.com/img/a/AVvXsEhaVmEPk6IpG982E_LOTVPo50tmdpz9hFGdZWPT3uU6j2T5X4alYECCtwWsgJjW5STMuxboK924nhbaaKT8Cpv_dv1ti5O-Yac49qvElqGHi3d-SHDqu0GMsv6vqU3FVR3bHQaf7S98-vmTZbFc58z0LXd_xbYgqkDuRs5YWxrxuR7h_OebUqn38KIO=w400-h223
https://blogger.googleusercontent.com/img/a/AVvXsEhaVmEPk6IpG982E_LOTVPo50tmdpz9hFGdZWPT3uU6j2T5X4alYECCtwWsgJjW5STMuxboK924nhbaaKT8Cpv_dv1ti5O-Yac49qvElqGHi3d-SHDqu0GMsv6vqU3FVR3bHQaf7S98-vmTZbFc58z0LXd_xbYgqkDuRs5YWxrxuR7h_OebUqn38KIO=s72-w400-c-h223
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