[Java] How to use the HashMap class

What is Map

Map is an interface called java.util.Map, which is a data structure used when you want to handle a set of keys and values ​​in Java. By using the Map interface, data structures such as HashMap and` `LinkedHashMap can be handled in a unified manner. In this article, I will write about how to use the HashMap class.

How to use the Map interface

Create your own class to implement the Map interface, or use an implementation class like HashMap or LinkedHashMap. You cannot register the same key more than once in the Map, and each key can only be mapped to one value.

Features of the HashMap class

■ ** Key order is not guaranteed ** ■ ** Key duplication is not allowed ** ■ ** Values ​​can be duplicated **

Declaration method

The declaration of the HashMap class is described as follows. Data type on the right side can be omitted by type inference The value can have List, Set, Map, and the key can be a class.

Map<Key model name,Value type name>Object name= new HashMap<>();
Map<String, List> map = new HashMap<>();  //Specify List as the value
Map<String, Set> map = new HashMap<>();   //Specify Set as the value
Map<String, Map<Integer, Object>> map = new HashMap<>();  //Specify Map as the value
Map<Example>, List> map = new HashMap<>();  //Specify a class called Example as a key

How to use

Specify the key and add the value (put method)

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");
	}
 }

If the key has already been mapped, it will be overwritten, and if there is no mapping, "null" will be returned.

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("dog", "Cat");
		System.out.println(animal.get("dog")); //Cat
		System.out.println(animal.get("pig")); //null
	}
 }

Get the value by specifying the key (get method)

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");
		System.out.println(animal.get("cat")); //Cat
	}
 }

Get all keys and values ​​(keySet method)

You can get all the Map keys by using the keySet method. Since the keySet method returns the Map key as a Set type, you can get all the keys by repeating the following using the extended for statement.

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");

		for (String pet : animal.keySet()) {
			System.out.println(pet);// monkey dog cat
		}
	}
 }

Get all values ​​(values ​​method)

You can get all the values ​​of Map by using the values ​​method. Since the values ​​method also returns the Map key as a Set type, you can get all the values ​​like the keySet method by using the extended for statement.

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");

		for (String pet : animal.values()) {
			System.out.println(pet);//Monkey dog ​​cat
		}
	}
 }

Get the number of elements (size method)

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");

		System.out.println(animal.size()); // 3
	}
 }

Returns a boolean value for the specified key (containsKey method)

Use the containsKey method to determine if a particular key is included in the map.

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");
		if (animal.containsKey("dog")) { // true
			System.out.println("Includes dog"); // Includes dog
		}
	}
 }

Returns a boolean value for the specified value (containsValue method)

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");
		if (animal.containsValue("monkey")) { // true
			System.out.println("Contains monkey"); // Contains monkey
		}
	}
 }

Returns empty or boolean (isEmpty method)

public class Sample {
	public static void main(String[] args) {
		Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");
		animal.clear();
		if (animal.isEmpty()) { // true
			System.out.println("It's empty"); // It's empty
		}
	}
 }

Process the elements in order (forEach method)

public class Sample {
    public static void main(String[] args) {
        Map<String,String> animal = new HashMap<>();
		animal.put("monkey", "monkey");
		animal.put("dog", "dog");
		animal.put("cat", "Cat");
        animal.forEach((key,value) -> System.out.println(key + " " + value)));
        //monkey monkey
        //dog dog
        //cat cat
    }
 }

reference

Java Platform SE 8 Interface Map (https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html)

Recommended Posts

[Java] How to use the HashMap class
[Java] How to use the File class
[Processing × Java] How to use the class
[Java] How to use the Calendar class
How to use java class
How to use the wrapper class
[Java] How to use LinkedHashMap class
How to use class methods [Java]
[Java] How to use Math class
[Java] How to use the hasNext function
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
How to use Java Scanner class (Note)
[Processing × Java] How to use the function
[Java] How to use Map
[Java] How to use FileReader class and BufferedReader class
[Java] How to use Thread.sleep to pause the program
How to use java Optional
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to use string.format
How to use Java Map
How to use the replace () method (Java Silver)
How to use Java variables
[Java] How to use Optional ①
[Java] How to use Calendar class and Date class
[Java] How to use compareTo method of Date class
[Java] How to get the maximum value of HashMap
How to use the link_to method
How to use Java HttpClient (Get)
How to use the include? method
How to use the form_with method
How to disassemble Java class files
How to use Java HttpClient (Post)
[Java] How to use join method
[Processing × Java] How to use variables
How to decompile java class files
[JavaFX] [Java8] How to use GridPane
[Java] How to use List [ArrayList]
How to use classes in Java?
[Processing × Java] How to use arrays
How to use Java lambda expressions
How to use Java enum type
Java HashMap class
How to get the class name / method name running in Java
Multilingual Locale in Java How to use Locale
How to use submit method (Java Silver)
[Rails] How to use the map method
[Easy-to-understand explanation! ] How to use Java instance
[Java] How to set the Date time to 00:00:00
[Java] How to get the current directory
How to use Java classes, definitions, import
[Easy-to-understand explanation! ] How to use Java polymorphism
[Java] [Maven3] Summary of how to use Maven3
How to install the legacy version [Java]
How to get the date in java
[Easy-to-understand explanation! ] How to use ArrayList [Java]
[Java] Learn how to use Optional correctly
[Easy-to-understand explanation! ] How to use Java overload
try-catch-finally exception handling How to use java