How to use Java Map

Introduction

I was studying in the introduction to Servlet & JSP that I can understand clearly and used it casually I thought I knew HashMap </ b>, so I summarized it.

How to use Map

A map stores two pieces of information as a pair of key and value.

  • The combination of key and data is called an entry.

  • Using the HashMap class </ b>

HashMap instantiation



Map<Key type,Value type>Map variables= new HashMap<Key type,Value type>(); //Use of generic type (JDK1.5)

Map<Key type,Value type>Map variables= new HashMap<>(); //Omit type argument (JDK1.7)

  • Specify the key and value data types.
  • For int type, use Integer </ b>.

In addition, HashMap has the following methods.

Return value Method meaning
put(●, ▲) Store ● and ▲ pairs on the map
get(●) Get the value corresponding to the key value
int size() Count the number of stored pairs
remove(●) Delete the element with the specified content
Set<●> keySet() Returns a list of stored keys

There are many more, so please refer to this link. .. ..

Note: Map allows duplicate values but not key duplicates </ b>.

Sample code

Main.java



import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Map<String, Integer> prefs = new HashMap<String, Integer>();
        prefs.put("Kyoto", 255);  //Store element
        prefs.put("Tokyo", 1261);
        prefs.put("Kumamoto Prefecture", 181);
        
        System.out.println(prefs.get("Kyoto"));  //Extract elements
        
        int Tokyo = prefs.get("Tokyo");  //Specify the key, retrieve the element and assign
        System.out.println(Tokyo);
        
        prefs.put("Tokyo", 1500);  //Explanation ①
        System.out.println(prefs.get("Tokyo"));
        
        prefs.remove("Kumamoto Prefecture");  //Delete element
        System.out.println(prefs.size());  //Get the number of stored pairs
        
    }
}

Output result



255
1261
1500
2

Explanation (1): If you put () different values with the same key, the values will be overwritten.

Finally

It will hurt if you think you understand. .. Lol

Recommended Posts