Java 8 forEach List and Map examples

We will iterate with forEach a java.util.List and we will create a java.util.Map from that list, after that we will iterate the Map with forEach

We will define the list :

        List<String> theListToIterate = Arrays.asList("We ", "will ", "iterate ","a ","List ", "as ", "Example ");



 the output : We will iterate a List as Example

We want to reuse the code, let create a Map from that list :

        Map<Integer, String> mapToIterate =
                Collectors.toMap(theListToIterate::indexOf,s -> s)

finally we have a map , so we have what to iterate 

Map.forEach :

        mapToIterate.forEach((integer, s) -> System.out.print(integer + s));


Category: Java Tutorials