Java - How to use HashMap.forEach() and examples

You can use forEach() when traversing HashMap. forEach() takes functional interface as an argument as follows.

public void forEach(BiConsumer<? super K, ? super V> action)

BiConsumer is a functional interface that takes two arguments and does not return. So you can pass the argument as a lambda expression. The first argument is key, and the second argument is value.

The following is an example of printing key and value with forEach. If you look at the lambda expression, key and value are passed as arguments, and there is no return value.

Map<String, Integer> fruits = new HashMap<>();
fruits.put("apple", 1);
fruits.put("banana", 2);
fruits.put("kiwi", 3);

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

// key: banana, value: 2
// key: apple, value: 1
// key: kiwi, value: 3

Because it supports Java8`s functional interface, you need to know about lambda expression, Functional Interface.

EntrySet.forEach()

HashMaps EntrySet class also has a forEach()method. If you look at the argument, it receives a functional interface calledConsumer` as an argument.

final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
  ...
  public final void forEach(Consumer<? super Map.Entry<K,V>> action)
  ...
}

Consumer is a functional interface that takes 1 argument and does not return.

The following is an example that outputs the same result as above. If you look at the lambda expression, it receives one Entry object as an argument.

Map<String, Integer> fruits = new HashMap<>();
fruits.put("apple", 1);
fruits.put("banana", 2);
fruits.put("kiwi", 3);

fruits.entrySet().forEach((entry) -> System.out.println(
        "key: " + entry.getKey() + ", value: " + entry.getValue()));

// key: banana, value: 2
// key: apple, value: 1
// key: kiwi, value: 3

KeySet.forEach(), Values.forEach()

HashMaps KeySet and Values classes also have a forEach()method. It takes a functional interface calledConsumer` as an argument.

public final void forEach(Consumer<? super V> action)

You can use it like this:

Map<String, Integer> fruits = new HashMap<>();
fruits.put("apple", 1);
fruits.put("banana", 2);
fruits.put("kiwi", 3);

fruits.keySet().forEach((key) -> System.out.println("key: " + key));
fruits.values().forEach((value) -> System.out.println("value: " + value));

// key: banana
// key: apple
// key: kiwi
// value: 2
// value: 1
// value: 3

Reference

codechachaCopyright ©2019 codechacha