For Each

Collections Interface provides data structures such as List and Set to store values and Map Interface provides methods to store key-value pairs. Looping or Iteration over the Collections and Map is one of the important aspects of Collections. Prior to Java 8, List and Set could be looped via enhanced for loop and Map could be iterated using Entry Set.

package org.wesome.java8;

import java.util.*;

class Apple {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Macintosh");
        map.put(2, "Fuji");
        map.put(3, "Gala");
        map.put(4, "Jonagold");

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("key = " + entry.getKey() + " value = " + entry.getValue());
        }

        List<Integer> list = Arrays.asList(1, 2, 3, 4);
        for (Integer integer : list) {
            System.out.println("integer = " + integer);
        }

        Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4));
        for (Integer integer : set) {
            System.out.println("integer = " + integer);
        }
    }
}

Java 8 introduced forEach method for Collections ie List and Set as well as for Map also.

package org.wesome.java8;

import java.util.*;

class Apple {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Macintosh");
        map.put(2, "Fuji");
        map.put(3, "Gala");
        map.put(4, "Jonagold");

        map.forEach((key, value) -> System.out.println("Key : " + key + " Value : " + value));

        List<Integer> list = Arrays.asList(1, 2, 3, 4);
        list.forEach(integer -> System.out.println("integer = " + integer));

        Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4));
        set.forEach(integer -> System.out.println("integer = " + integer));
    }
}

 

follow us on