Posts

Showing posts with the label forEach

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 {