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
More topics,