Java 8 - forEach method that iterates with an index of an Array or List

In this section we will demonstrate how we can use the forEach() method with a specific index of an Array or List.

1. forEach() Method with an Array Index

Generate the index with IntStream.range.

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

public class Main {

public static void main(String[] args) {

// Creating a list of string
String[] list = { "Java", "Kotlin", "Go", "Ruby" };

// Using forEach with index
List<String> collect = IntStream.range(0, list.length)
.mapToObj(index -> index + ":" + list[index])
.collect(Collectors.toList());

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

}
}


Console Output:
0:Java
1:Kotlin
2:Go
3:Ruby

2. forEach() Method with a List and HashMap Index

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

public class Main {

public static void main(String[] args) {

// Creating a list of string
List<String> list = Arrays.asList("Java", "Kotlin", "Ruby", "C", "php");

// Put the List of String to the HashMap
HashMap<Integer, String> collect = list.stream().
collect(HashMap<Integer, String>::new,
(map, streamValue) -> map.put(map.size(),
streamValue), (map, map2) -> {});
//using forEach with index
collect.forEach((k, v) -> System.out.println(k + ":" + v));
}
}


Console Output:
0:Java
1:Kotlin
2:Ruby
3:C
4:php

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete