January 5, 2021 A brief summary of how to handle Maps in Java.
Map can store multiple data consisting of two elements, key and value. A key is like giving a name to a value, and each value has a key. The feature of Map is that this key and value are paired. Therefore, when searching for a value from Map, you can search for the key as a marker.
Map is an interface, so you have to use a class that implements it to instantiate it. The HashMap class is often used to instantiate a Map.
How to declare using the HashMap class
Map<Key model name,Value type name>Object name= new HashMap<>();
You must specify the key and value data types when declaring.
Sample code
import java.util.HashMap;
import java.util.Map;
public class Sample {
public static void main(String[] args) throws Exception {
//When the key is Integer and the value is String
Map<Integer, String> map = new HashMap<>();
}
}
A method that can add data to Map, specify the key in the first argument and the value in the second argument.
Sample code
import java.util.HashMap;
import java.util.Map;
public class Sample {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Tanaka");
map.put(3, "Suzuki");
map.put(5, "Yamada");
}
}
It is a method that can get the data stored in Map, and you can get the value of the key by specifying the key in the argument.
Sample code
import java.util.HashMap;
import java.util.Map;
public class Sample {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Tanaka");
map.put(3, "Suzuki");
map.put(5, "Yamada");
System.out.println(map.get(1));
System.out.println(map.get(3));
System.out.println(map.get(5));
}
}
Execution result
Tanaka
Suzuki
Yamada
A method that returns the value of the key contained in the Map. This time, I will introduce how to output all the keys of Map using the keySet method.
Sample code
import java.util.HashMap;
import java.util.Map;
public class Sample {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Tanaka");
map.put(3, "Suzuki");
map.put(5, "Yamada");
for(Integer key:map.keySet()) {
System.out.println(key);
}
}
}
Execution result
1
3
5
The values method can receive the defined Map and enumerator collectively. If you want to get all the values of Map, use values method.
Sample code
#### **`Sample code`**
```java
import java.util.HashMap;
import java.util.Map;
public class Sample {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put (1, "Tanaka");
map.put (3, "Suzuki");
map.put (5, "Yamada");
for(String values: map.values()) {
System.out.println(values);
}
}
}
Execution result
Tanaka
Suzuki
Yamada
#References [For beginners] Explain how to use Java map! Introducing sample code! [Introduction to Java] Summary of how to use Map(Initialize with HashMap, sort values)
Recommended Posts