Java 8 forEach() Map Example

Java 8 provides a new method forEach() to iterate the elements. It is defined in the Iterable and Stream interface.

It is a default method defined in the Iterable interface. Collection classes that extend the Iterable interface can use the forEach() loop to iterate elements.

Java 8 forEach() method with the Map Example

Let's first see the normal way to loop a Map using a for-each loop.
public static void forEachWithMap() {

    // Before Java 8, how to loop map
    final Map < Integer, Person > map = new HashMap < > ();
    map.put(1, new Person(100, "Ramesh"));
    map.put(2, new Person(100, "Ram"));
    map.put(3, new Person(100, "Prakash"));
    map.put(4, new Person(100, "Amir"));
    map.put(5, new Person(100, "Sharuk"));

    for (final Entry < Integer, Person > entry: map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue().getName());
    }
}
In Java 8, you can loop a Map with forEach and lambda expressions.
public static void forEachWithMap() {

    // Before Java 8, how to loop map
    final Map < Integer, Person > map = new HashMap < > ();
    map.put(1, new Person(100, "Ramesh"));
    map.put(2, new Person(100, "Ram"));
    map.put(3, new Person(100, "Prakash"));
    map.put(4, new Person(100, "Amir"));
    map.put(5, new Person(100, "Sharuk"));

    //  In Java 8, you can loop a Map with forEach + lambda expression.
    map.forEach((k, p) - > {
        System.out.println(k);
        System.out.println(p.getName());
    });
}

Reference


Related HashMap Source Code Examples


Comments