[Java] [Java] Method of repeatedly obtaining the key and value stored in Map

3 minute read

Front

In this article, I will introduce some methods to retrieve the key and value stored in Map regardless of the implementation in an iterative process. The audience for this article is primarily beginner to intermediate.

I think that you often use list data structure such as ArrayList and LinkedList as a way to manage the collected information when programming, but by using the data structure of Map, you can make more complicated problems easier. Since it will be able to handle it, I definitely want you to learn how to use it.

Main acquisition method

Mainly there are the following methods to get the key and value from the collection of Map structure in the iteration process.

  • Use EntrySet
  • Use forEach(BiConsumer<T,U>) method (JDK 1.8 or later)

How to use #EntrySet

It may not be so familiar to us now, but by using EntrySet you can easily get the keys and values stored in a Map in an iterative process.

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public final class TestEntrySet {

    public static void main(String[] args) {
        final Map<String, String> testMap = new HashMap<>(3);
        testEntrySet.put("test1", "value1");
        testEntrySet.put("test2", "value2");
        testEntrySet.put("test3", "value3");

        final Set<Entry<String, String>> testEntrySet = testMap.entrySet();

        for (Map.Entry<String, String> entry :testEntrySet) {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
    }
}

In the above sample code, the test Map implemented in HashMap is declared, the test values are set, and then the entrySet() method is called.

You can get an EntrySet of type Set<Entry<String, String>> by calling the entrySet() method. Use the EntrySet obtained here in the extended for statement. Of course, in the above sample code, EntrySet is obtained before iterating, but you can also obtain EntrySet when using the extension for as follows.

// Get EntrySet when defining extended for statement
for (Map.Entry<String, String> entry :testMap.entrySet()) {
}

You can get the key stored in Map by using the getKey() method in the iteration and the value stored in Map by using the getValue() method.

Therefore, the execution result of the above sample code is output as follows.

test1
value1
test2
value2
test3
value3

How to use the #forEach method

Perhaps the method using the forEach() method is more mainstream than the iteration method using the EntrySet introduced above. This forEach() method is a relatively new method implemented in JDK1.8 with the addition of a functional interface, which makes it possible to operate iteratively more intuitively than EntrySet.

import java.util.HashMap;
import java.util.Map;

public final class TestForEach {

    public static void main(String[] args) {
        final Map<String, String> testMap = new HashMap<>(3);
        testEntrySet.put("test1", "value1");
        testEntrySet.put("test2", "value2");
        testEntrySet.put("test3", "value3");

        // pass the lambda expression that implements BiConsumer<T, U> as an argument
        testMap.forEach((key, value) -> {
            System.out.println(key);
            System.out.println(value);
        });
    }
}

At first glance, you will find that it is a more concise way of writing than using the EntrySet.

What seems difficult is the argument, but you pass the lambda expression that implements the functional interface BiConsumer<T,U> as the argument to the forEach() method. I will omit about the lambda expression and the functional interface because it deviates from the purpose of this article, but when using the forEach() method in Map, it is ok to remember the above sample code.

The variable name specified in the lambda expression can be changed arbitrarily. In the above sample code, the key of Map is stored in key and the value of Map is stored in value.

Therefore, the execution result of the above sample code is as follows when using EntrySet.

test1
value1
test2
value2
test3
value3

important point

Due to the characteristics of BiConsumer<T,U> which is a functional interface, it is not possible to return the return value in the iteration process using the forEach() method. Some of the functional interfaces return values, but the forEach() method just repeats the process for the size of the Map.

For example, if you want to return false as a boolean value when an error is detected in the iteration process of Map, we recommend using EntrySet instead of forEach().