TreeMap forEach(BiConsumer) in Java

forEach(BiConsumer): This method is available in java.util.TreeMap class of Java.

Syntax:

void java.util.TreeMap.forEach(BiConsumer<? super K, ? super V> action)

This method takes one argument. This method performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

Parameters: One parameter is required for this method.

action: The action to be performed for each entry.

Exceptions: NA

Approach

Java

import java.util.TreeMap;

public class TreeMapforEach {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

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

    }
}

Output:

Key : 2 Value : HelloKey : 6 Value : C++Key : 11 Value : JavaKey : 23 Value : ProgramKey : 25 Value : Program


No comments:

Post a Comment