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

Comments

Popular posts from this blog

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

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

Java - Blowfish Encryption and decryption Example

Java - DES Encryption and Decryption example

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

ReactJS - Bootstrap - Buttons

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java - How to Count the Number of Occurrences of Substring in a String

Top 5 Java ORM tools - 2024