Java 8 Foreach With Index – Detailed Guide

Java 8 Stream Foreach is a terminal operation and helps in iterating over each element of a stream.

In Java 8, Foreach with index is not available by default while iterating through the stream.
You can use any of the following approaches to have an index while iterating through streams using foreach.

Using IntStream.range()

Java 8 IntStream.range() method returns sequential ordered IntStream by the incremental value of 1.
You can use the IntStream.range() method to generate the index and iterate through the object.
Code

    List<String> directions = Arrays.asList("North", "East", "South", "West");  
    IntStream.range(0, directions.size())  
            .forEach(index ->  
                    System.out.println("index: " + index + "   value: " + directions.get(index)  
                    )
                   
            );

Output

    index: 0   value: North
    index: 1   value: East
    index: 2   value: South
    index: 3   value: West

You can use this method, when you want to iterate a list in Java 8 foreach with Index.

Using IntStream.range() on list of objects

You can use IntStream.range() method to iterate the list of objects using Java 8 Foreach.
Code

employeeList = [{
                "name":"Max",
                "id":100
                },
                {
                "name":"Michael",
                "id":101
                },
                {
                "name":"Balu",
                "id":103
                },
                {
                "name":"Alex",
                "id":104
                }]
    List<String> employeeListWithIndex = IntStream.range(1, employeeList.size())
        .mapToObj(index -> "index: " + index + "  name: " + employeeList.get(index).getName())
        .collect(Collectors.toList());  

    employeeListWithIndex.forEach(System.out::println);

Output

    index: 1  name: Max
    index: 2  name: Michael
    index: 3  name: Balu
    index: 4  name: Alex

Using Map

Java 8 stream allows converting a List of Objects to Map(Key, Value) pairs.
You can use the below approach to convert a List to a Map, having the index of the list as the key in Map. Then the map can be used along with foreach to print the values with index.
Code

    List<String> directions = Arrays.asList("North", "East", "South", "West");  
    HashMap<Integer, String> directionsMap = directions  
        .stream()  
        .collect(HashMap::new,  
            (map, value) -> map.put(map.size(), value),  
            (map, map2) -> {  
            });  

    directionsMap.forEach((key, value) -> System.out.println("index: " + key + "   value: " + value));

Output

    index: 0   value: North
    index: 1   value: East
    index: 2   value: South
    index: 3   value: West

Related Topics

Leave a Comment