Reading Map Collection in One Minute

Map collection

1.1. Overview

In real life, we often see such a set: IP address and host name, ID number and individual, system user name and system user object, etc. This one-to-one correspondence is called mapping. Java provides a special collection class to store the object of this object relationship, namely the java.util.Map interface.

By looking at the description of the Map interface, we find that the collection under the Map interface is different from the collection under the Collection interface. They store data in different forms, as shown in the following figure.

  • In collections, elements exist in isolation (understood as singletons), and they are stored one by one in a Collection.
  • The set of elements in a Map exists in pairs (understood as husband and wife). Each element consists of a key and a value, through which the corresponding value can be found.
  • The set in Collection is called a single column set, and the set in Map is called a double column set.
  • It should be noted that the set in Map cannot contain duplicate keys, and the values can be duplicated; each key can only correspond to one value.

The characteristics of Map collections can be summarized as follows:

  1. A Map set is a two-column set, and an element contains two values (one key and one value).
  2. The data types of elements, key s and value s in a Map collection can be the same or different.
  3. key is not allowed to repeat elements in a Map collection, value is repeatable.
  4. The elements in the Map collection, key and value are one-to-one correspondences.

1.2. Common subclasses of Map collections

By looking at the description of Map interface, we can see that Map has many subclasses. Here we mainly discuss the commonly used HashMap collection and LinkedHashMap collection.

1.2.1. HashMap<K,V>:

Java.util.HashMap<k,v>set implements Map<k,v>interface

The hash table structure is used to store data, and the access order of elements can not be guaranteed to be consistent. To ensure that the keys are unique and not duplicated, the hashCode() method and equals() method of the keys need to be rewritten.

HashMap collection features:

  1. At the bottom of the HashMap collection is the hash table: the query speed is very fast

    Prior to JDK 1.8: Array + One-way Linked List

    After JDK 1.8: Array + One-way Link List / Red-Black Tree (Link List Length Over 8): Improve Query Speed

  2. HashMap collections are an unordered combination, and the order of storing and retrieving elements may be inconsistent.

1.2.2. LinkedHashMap<K,V>:

Java.util.LinkedHashMap<k,v>set extents HashMap<k,v>set
LinkedHashMap, a subclass of HashMap, uses hash table structure + linked list structure to store data. The access order of elements can be guaranteed by the linked list structure, and the hashCode() method and equals() method can be guaranteed to be unique and non-repetitive by the hash table structure without rewriting keys.

LinkedHashMap features:

  1. At the bottom of the LinkedHashMap collection is a hash table + linked list (ensuring the order of iterations)
  2. The LinkedHashMap set is an ordered set, and the stored and extracted elements are identical.

tips: The set in the Map interface has two generic variables < K, V>. When used, two generic variables are assigned data types. The data types of the two generic variables < K, V> can be the same or different.

1.3 Common Methods in Map Interface

There are many methods defined in Map interface, which are commonly used as follows:

  • public V put(K key, V value): Adds the specified key and value to the Map collection.
  • public V remove(Object key): Delete the key-value pair element corresponding to the specified key in the Map collection and return the value of the deleted element.
  • public V get(Object key) gets the corresponding value in the Map collection according to the specified key.
  • boolean containsKey(Object key) determines whether a collection contains the specified key.
  • Public Set < K > keySet (): Gets all the keys in the Map collection and stores them in the Set collection.
  • Public Set < Map. Entry < K, V > entrySet (): Gets the set of all key-value pair objects in the Map set (Set set).

Code demonstration:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapDemo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();

        /*public V put(K key, V value): Adds the specified key and value to the Map collection*/
        map.put("Huang Xiaoming", "Yang Ying");
        map.put("Wang Zulan", "Leanne");
        map.put("Nicholas Tse", "Cecilia Cheung");
        System.out.println( map.put("Nicholas Tse", "Cecilia Cheung")); // Cecilia Cheung
        System.out.println(map); // {Wang Zulan = Li Yaman, Xie Tingfeng = Cecilia Cheung, Huang Xiaoming = Yang Ying}
        map.put("Nicholas Tse", "Wang Fei");
        System.out.println(map);   // {Wang Zulan = Li Yaman, Xie Tingfeng = Wang Fei, Huang Xiaoming = Yang Ying}

        /*public V get(Object key) Gets the corresponding value in the Map collection according to the specified key.*/
        System.out.println(map.get("Nicholas Tse"));  // Wang Fei

        /*boolean containsKey(Object key) Determines whether the collection contains the specified key.*/
        System.out.println(map.containsKey("Wang Zulan"));  // true
        System.out.println(map.containsKey("Deer haw"));    // false

        /* public Set<K> keySet(): Gets all the keys in the Map collection and stores them in the Set collection.*/
        Set<String> mapSet = map.keySet();
        System.out.println(mapSet);    // [Wang Zulan, Tse Tingfeng, Huang Xiaoming]

        /*  public Set<Map.Entry<K,V>> entrySet(): Gets the set of all key-value-pair objects (Set sets) in the Map collection.*/
        Set<Map.Entry<String, String>> mapEntry = map.entrySet();
        System.out.println(mapEntry);   // [Wang Zulan = Li Yaman, Xie Tingfeng = Wang Fei, Huang Xiaoming = Yang Ying]
        
        /*public V remove(Object key): Returns the value of the deleted element by deleting the key-value pair element corresponding to the specified key in the Map collection.*/
        map.remove("Nicholas Tse");
        System.out.println(map);  // {Wang Zulan = Li Yaman, Huang Xiaoming = Yang Ying}
        
    }
}

tips:

When using put method, if the specified key does not exist in the collection, then there is no corresponding value of the key, return null, and add the specified key value to the collection;

If the specified key exists in the set, the return value is the value corresponding to the key in the set (the value before replacement), and the value corresponding to the specified key is replaced with the specified new value.

1.4 Map Set Traversal Key Value Finding Method

Key Value Finding: Get the corresponding value of the key through the key in the element

Analysis steps:

  1. Gets all the keys in the Map, and since the keys are unique, returns a Set collection to store all keys. Method hint: keyset()
  2. Traverse through the Set of keys to get each key.
  3. According to the key, get the corresponding value of the key. Method hint: get(K key)

Code demonstration:

public class MapDemo01 {
    public static void main(String[] args) {
        //Creating Map Collection Objects 
        HashMap<String, String> map = new HashMap<String,String>();
        //Add elements to collections 
         map.put("Hu Ge", "Huo Jianhua");
        map.put("Guo Degang", "Yu Qian");
        map.put("Joker Xue", "Dazhang Wei");

        //Get all the keys to get the keyset
        Set<String> keys = map.keySet();
        // Traverse the keyset to get each key
        for (String key : keys) {
          	//The key is the key.
            //Get the corresponding value
            String value = map.get(key);
            System.out.println(key+"Of CP Yes:"+value);
        }  
    }
}

Ergodic diagrams:

1.5 Map Set Traversal Key Value Pairs

1.5.1. Entry key-value pair object

Set < Map. Entry < k, V > entrySet (): Returns the Set view of the mapping relationship contained in this mapping.

We already know that there are two kinds of objects stored in Map, one is called key and the other is called value. They are one-to-one correspondence in Map. This pair of objects is also called an Entry in Map. Entry encapsulates the corresponding relationships of key-value pairs into objects. That is, the key-value pair object, so that when we traverse the Map collection, we can get the corresponding key and value from each key-value pair (Entry) object.

Since Entry represents a pair of keys and values, it also provides a way to obtain corresponding keys and corresponding values:

  • public K getKey(): Gets the key in the Entry object.
  • public V getValue(): Gets the value in the Entry object.

A method to obtain all Entry objects is also provided in the Map collection:

  • Public Set < Map. Entry < K, V > entrySet (): Gets the set of all key-value pair objects in the Map set (Set set).

1.5.2. How to implement key-value pair traversal?

Key-value pairing: Get the key and value in the key-value pair (Entry) object through each key-value pair (Entry) object in the set.

Operation steps and illustrations:

  1. Gets all the key-value pairs (Entry) objects in the Map collection and returns them as Set sets. Method Tip: entrySet().

  2. Traversing through the Set collection containing key-value pairs (Entry) objects, each key-value pair (Entry) object is obtained.

  3. Through the key-value pair (Entry) object, get the key and value in the Entry object. Method Tip: getkey() getValue()

public class MapDemo02 {
    public static void main(String[] args) {
        // Creating Map Collection Objects 
        HashMap<String, String> map = new HashMap<String,String>();
        // Add elements to collections 
        map.put("Hu Ge", "Huo Jianhua");
        map.put("Guo Degang", "Yu Qian");
        map.put("Joker Xue", "Dazhang Wei");

        // Get all entry objects entrySet
        Set<Entry<String,String>> entrySet = map.entrySet();

        // Traverse to get each entry object
        for (Entry<String, String> entry : entrySet) {
           	// analysis 
            String key = entry.getKey();
            String value = entry.getValue();  
            System.out.println(key+"Of CP yes:"+value);
        }
    }
}

Ergodic diagrams:

tips: Map collections cannot be traversed directly using iterators or foreach. But you can use it when you convert it to Set.

1.6 HashMap stores custom type keys

HashMap stores custom type keys, and the Map collection must guarantee its uniqueness.

Implementing method: As an element of key, hashCode method and equals method can be rewritten to ensure the uniqueness of key.

tip: If the key is a String type, you don't need to override hashCode and equals methods, because the String class has overridden both methods. Others have to rewrite hashCode and equals methods to ensure the uniqueness of keys.

Give an example:

Every student (name, age) has his or her own home address. Then, since there is a corresponding relationship, the student object and family address are stored in the map set. The student is the key and the family address is the value.

Note that students with the same name and age are considered to be the same student.

Write student classes:

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

    @Override
    public String toString() {
        return "StudentMap{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

Write test classes:

public class HashMapTest {
    public static void main(String[] args) {
        //1. Create Hashmap collection objects.
        Map<Student,String> stu= new HashMap<Student,String>();
        //2. Add elements.
        stu.put(new StudentMap("Dili Reba", 24), "Beijing");
        stu.put(new StudentMap("Gulinaza", 23), "Shanghai");
        stu.put(new StudentMap("Ouyang Nana", 19), "Shenzhen");
        
        //3. Take out the elements. Key Value Finding Method
        Set<Student>keySet = stu.keySet();
        for(Student key: keySet){
            value = stu.get(key);
            System.out.println(key.toString()+"......."+value);
        }
    }
}
// Operation results
StudentMap{name='Ouyang Nana', age=19}........Shenzhen
StudentMap{name='Dili Reba', age=24}........Beijing
StudentMap{name='Gulinaza', age=23}........Shanghai
  • When storing custom objects in HashMap, if the custom objects exist as key s, then to ensure that the objects are unique, the hashCode and equals methods of the objects must be copied (if forgotten, please review) HashSet stores custom objects).
  • If you want to ensure that the key s stored in the map are in the same order as those taken out, you can use the java.util.LinkedHashMap collection to store them.

1.8 LinkedHashMap

We know that HashMap guarantees the uniqueness of paired elements, and the query speed is very fast, but there is no order for paired elements to be stored in. So what should we do to ensure orderliness and speed?

Under HashMap, there is a subclass LinkedHashMap, which is a data storage structure composed of linked list and hash table. Yes?

Keywords: Java JDK

Added by r00tk1LL on Mon, 22 Jul 2019 11:14:42 +0300