Basic usage of HashMap

1, Structure of HashMap

HashMap adopts the data structure of array and linked list, which is convenient for query and modification. It inherits the linear search of array and the addressing modification of linked list. Its stored content is key value mapping.

2, Inheritance class of HashMap

3, Key and Value type settings

The key and value types of HashMap can be the same or different.
It can be key and value of String type, or key of Integer type and value of String type.

The packing class corresponding to the basic type is as follows:

Basic typereference type
booleanBoolean
byteByte
shortShort
intInteger
longLong
charCharacter
floatFloat
doubleDouble

ex:
In the following example, set key to Integer type and value to String type.

 HashMap<Integer, String> map = Map.of(1,"one",2,"two",3,"three");
keyvalue
1one
2two
2three

4, General usage

1. Introduction class

import java.util.HashMap;   // Introduce HashMap class

2. Initialization

HashMap<Integer, String> Sites = new HashMap<Integer, String>();

3. Common methods
(1) Add element: put() method

 HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");

(2) Access element: get() method

HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        //Print access element
        System.out.println(Sites.get(3));

(3) Delete element: remove() method
Delete the key value pair corresponding to the key

HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        //Delete element
        Sites.remove(4);

(4) Delete all HashMap: clear() methods
Delete all key value pairs and clear the entire data structure.

HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        //Delete all key value pairs
        Sites.clear();

(5) Calculate size: size() method

// Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        System.out.println(Sites.size());

(6) Whether there is a mapping relationship: isEmpty() method
If the HashMap does not contain any mapping relationship of key / value pairs, it returns true; otherwise, it returns false.

// Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        
        result = sites.isEmpty(); // true
        //Returns true if the HashMap does not contain any key / value pair mapping relationships
        //Otherwise, false is returned.

(7) Check whether there is a mapping relationship corresponding to the key: containsKey() method
The containsKey() method checks whether there is a mapping relationship corresponding to the specified key in the hashMap.
If there is a mapping relationship corresponding to the specified key in the hashMap, return true; otherwise, return false.

// Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        
        if(sites.containsKey(1)) {
            System.out.println("key Is 1 exists in sites in");
        }  //Judge whether the mapping relationship with key 1 exists.
        if(!sites.containsKey(5)) {
            sites.put(5, "Wiki");
        }  //If the mapping relationship with key 5 does not exist, the mapping relationship with key 5 is inserted.
        

(8) Check whether there is a mapping relationship corresponding to value: containsValue() method
The containsValue() method checks whether there is a mapping relationship corresponding to the specified value in the hashMap.
If there is a mapping relationship corresponding to the specified value in the hashMap, return true; otherwise, return false.

// Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        
        if(sites.containsValue("Runoob")) {
            System.out.println("Runoob Exist in sites in");
        }//Judge whether the mapping relationship with value "Runoob" exists.
        if(!sites.containsValue("Wiki")) {
            sites.put(sites.size(), "Wiki");
        }//If the mapping relationship with value "Wiki" does not exist, insert the mapping relationship with value "Wiki".
        

5, Get the key or value set

1. Get the key set
The Map collection provides us with two methods of obtaining values:

(1)keySet():
Return value type: Set < Object > method is keySet(); Return the Set view containing keys in this Map and store all keys in the Map into the Set set. Because Set has iterators, take out all keys in an iterative way, and then take out the corresponding values according to the get() method.

(2)entrySet():
Return value type: set < map. Entry < K, V > > the method is entrySet(). This method takes out the relationship, which contains key and value, where map. Entry < K, V > represents the data type.
That is, save the mapping relationship in the Map Set into the data type Map.Entry of this relationship in the Set.

methodprocess
keySet()First get the collection of all keys, and then get the corresponding values according to the keys.
entrySet()First, the Key Value relationship in the map is obtained and encapsulated into entry objects, which are stored in a Set set. Then, the Set set is iterated, and the user-defined objects are stored in the Set according to the corresponding Key and Value obtained from the entry.

<1> Get: use the keySet() method to return the Set view composed of all keys in the map.

// Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // Add key value pair
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");

<2> Use the entrySet() method to return the Set view of the mapping contained in the mapping.

    for(HashMap.Entry<Integer,Integer> entry : Sites.entrySet()) {
            System.out.println(entry.getKey());
        }

2. Traversal
(1) . use iterators for traversal.

        //obtain
        Set set = Sites.KeySet(); //Use the Set() function to obtain all key values in the newmap
        
        //ergodic
        Iterator  ite = Sites.iterator();   // Create an iterator called ite
        while(ite.hasNext()){  // Use hasNext() to determine whether the next element exists
             System.our.println((String)ite.Next());               
             // ! This sentence is the Key. After the Key value is obtained, it can be output only after forced type conversion  
             newmap.get(ite.Next()).showStudent();    
             //  The first call to Next() returns the key value of the first element in newmap
             // The next call returns the key value of the next element

(2) for loop direct access.
This method is mostly used for direct access, with few more key setting operations. On the contrary, it is easier to use iterators for repeated access, comparison, search and other operations.

   for(int key : Sites.keySet()){
			System.out.println(key);
	}

3. Get value
Get the value Collection through the values method. Because value can be repeated, the returned type is Collection// Note that the type is Collection

    Collection<Integer> values = map.values();
		for(Integer i : values)
			System.out.println(i);	
	}

Keywords: Java

Added by harnacks on Fri, 22 Oct 2021 07:30:12 +0300