[Java] How to get the key and value stored in Map by iterative processing

First stage

In this article, I will introduce some ways to get the keys and values stored in Map in the iterative process regardless of implementation. The target readers of this article are mainly beginners to intermediates.

I think that there are many situations where you use list data structures such as ʻArrayList and LinkedList` as a way to manage a large amount of information when programming, but by mastering the data structure of Map, you can easily solve more complicated problems. I would like you to learn how to use it because you will be able to handle it.

Main acquisition method

There are mainly the following methods to get the key and value from the collection of Map structure in the iterative process.

--Use ʻEntrySet --Use theforEach (BiConsumer <T, U>)` method (JDK 1.8 or later)

How to use EntrySet

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

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 map for the test implemented by HashMap is declared, the value for the test is set, and then the ʻentrySet ()` method is called.

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

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

You can get the key stored in the Map by using the getKey () method in the iterative process, and the value stored in the 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 this forEach () method is now more mainstream than the iterative process using ʻEntrySetintroduced earlier. ThisforEach () method is a relatively new method implemented in JDK1.8 with the addition of functional interfaces, and is now more intuitive 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");

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

At first glance, you'll find that it's more concise than the ʻEntrySet` method.

The point that seems difficult is the argument, but the argument of the forEach () method is passed a lambda expression that implements the functional interface BiConsumer <T, U>. I will omit the lambda expression and functional interface because they deviate from the purpose of this article, but when using the forEach () method in Map, it is okay if you remember how to write the above sample code.

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

Therefore, the execution result of the above sample code will be as follows as when using ʻEntrySet`.

test1
value1
test2
value2
test3
value3

important point

Due to the characteristics of the functional interface BiConsumer <T, U>, the return value cannot be returned in the iterative process using the forEach () method. Some functional interfaces return a value, 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 iterative process of Map, we recommend using ʻEntrySet instead of forEach () `.

Recommended Posts

[Java] How to get the key and value stored in Map by iterative processing
[Java] Various methods to acquire the value stored in List by iterative processing
How to create your own annotation in Java and get the value
How to get the date in java
How to increment the value of Map in one line in Java
[Ruby] How to get the value by specifying the key. Differences between hashes, symbols and fetch
How to get the value after "_" in Windows batch like Java -version
[Java] How to get the maximum value of HashMap
How to get the class name / method name running in Java
How to set tabs and spaces to be visible by using the tab key to insert spaces in Java files in Eclipse
[ruby] How to assign a value to a hash by referring to the value and key of another hash
[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.
How to get the id of PRIMAY KEY auto_incremented in MyBatis
[Java] How to convert from String to Path type and get the path
How to encrypt and decrypt with RSA public key in Java
How to get the length of an audio file in java
Duplicate Map sorted by key in Java
Reverse Key from Value in Java Map
[Processing × Java] How to use the loop
[Java] How to get the current directory
[Processing × Java] How to use the class
[Processing × Java] How to use the function
Web application structure by Java and processing flow in the presentation layer
[Java] How to get the current date and time and specify the display format
How to get the setting value (property value) from the database in Spring Framework
How to get the absolute path of a directory running in Java
Use MyBatis to get Map with key as identifier and value as Entity
[Java] How to get and output standard input
How to get Class from Element in Java
How to get and study java SE8 Gold
[Java] How to get the redirected final URL
[Java] How to get the authority of the folder
I want to get the value in Ruby
How to embed and display youtube videos in Rails (You can also get the URL you entered by editing)
[Java] How to get the URL of the transition source
[Java] How to omit the private constructor in Lombok
Source used to get the redirect source URL in Java
[Java] How to get a request by HTTP communication
Java classes and instances to understand in the figure
How to convert A to a and a to A using AND and OR in Java
[Ruby] How to get the tens place and the ones place
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
# 1_JAVA I want to get the index number by specifying one character in the character string.
[Java] How to display the day of the week acquired by LocalDate, DateTimeformatter in Japanese
[Java] How to use Map
[Java] How to use Map
How to use Java Map
[Java] Get Map key / value pairs using extended for statement
Difference between Java and JavaScript (how to find the average)
How to connect the strings in the List separated by commas
[Rails] How to define macros in Rspec and standardize processing
How to retrieve the hash value in an array in Ruby
What happened in "Java 8 to Java 11" and how to build an environment
How to call and use API in Java (Spring Boot)
How to develop and register a Sota app in Java
How to derive the last day of the month in Java
Differences in how to handle strings between Java and Perl
How to switch Java in the OpenJDK era on Mac
[Rails] How to display information stored in the database in view
How to write comments in the schema definition file in GraphQL Java and reflect them in GraphQL and GraphQL Playground
Filter the Java No. 2 Optional list that was useful in business and get the first value