Those unknown secrets about Map collection

Keywords: Java set

preface

In the last issue, we talked about the Collection Set. It is a single column Set, which is divided into List Set and Set set Set. Today, I will continue to analyze a double column Set, that is, Map. Why is it called a double column Set? Look down and you'll see.  

catalogue

1, Map

2, Basic concepts of HashMap

  3, Basic method and use of HashMap set

4, Traversal of HashMap collection

5, Comprehensive case of HashMap set

6, Summary

1, Map

        Characteristics of Map set
    - Key value pair mapping
    - A key corresponds to a value
    - The key cannot be repeated, and the value can be repeated
    - Element access disorder

         We understand it through one of his implementation classes, the HashMap collection

2, Basic concepts of HashMap

        Definition of HashMap:     

         HashMap is a hash table that stores key value mappings.

         HashMap implements the Map interface, stores data according to the HashCode value of the key, has fast access speed, allows the key of one record to be null at most, and does not support thread synchronization.

         HashMap is unordered, that is, the insertion order is not recorded.

         HashMap inherits from AbstractMap and implements Map, Cloneable and java.io.Serializable interfaces.

The key and value types of HashMap can be String or other data wrapper types. When it comes to wrapper types, let's review the wrapper types by the way:

        

 

  3, Basic method and use of HashMap set

        After learning the basic concepts of HashMap set, how can we use it in the actual development process? We're going to use his unique method here,

The following are common methods for HashMap collections

           

 

         It should be noted that the addition of elements in the Map Collection is not the add () method of the Collection, but the Put() method. Because the Map set is a set of key value pairs, how do we get each element in the set? Here, the Collection also provides us with its element acquisition method:

  The example code is as follows:

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

/*
    Map Collection acquisition function:
        V get(Object key):Get value according to key
        Set<K> keySet():Gets a collection of all keys
        Collection<V> values():Gets a collection of all values
 */
public class MapDemo03 {
    public static void main(String[] args) {
        Map<String, String> m = new HashMap<String, String>();

        m.put("Zhang San", "Li Si");
        m.put("Wang Wu", "Zhao Liu");
        m.put("Boss Li", "Bald head strength");
        // V get(Object key): get the value according to the key
        System.out.println(m.get("Zhang San"));

        System.out.println(m.get("Zhang Si"));
        System.out.println("=============");

        //        Set < k > keyset(): get the set of all keys
        Set<String> s = m.keySet();
        for (String i : s) {
            System.out.println(i);
        }
        System.out.println("=============");

        //        Collection < V > values(): get the collection of all values
        Collection<String> c = m.values();
        for (String x : c) {
            System.out.println(x);
        }
    }
}

  Output results:

Li Si
null
=============
Zhang San
Wang Wu
Boss Li
=============
Li Si
Zhao Liu
Bald head strength

4, Traversal of HashMap collection

        In fact, traversal is nothing more than taking out the elements in the set one by one, which we can use. In the third part, we have actually talked about an traversal method, that is, we get the set of keys, and then use the loop to get the value corresponding to each key, so that we can take out each element in the set.

        Traversal method 1: find the value according to the set of keys

Step analysis
    - Gets a collection of all keys. Using keySet() method
    - Traverse the collection of keys and get each key. Implementation with enhanced for  
    - Find the value according to the key. It is implemented by get(Object key) method

code implementation

        

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

/*
    Map Traversal of collection (mode 1):
        1:Gets a collection of all keys. Using keySet() method
        2:Traverse the collection of keys and get each key. Implementation with enhanced for
        3:Find the value according to the key. It is implemented by get(Object key) method
 */
public class MapDemo01 {
    public static void main(String[] args) {
        //Create collection object
        Map<String, String> map = new HashMap<String, String>();

        //Add element
        map.put("zhang wuji", "Zhao Min");
        map.put("Guo Jing", "Huang Rong");
        map.put("Guo Yang", "little dragon maiden");
        //1: Gets a collection of all keys. Using keySet() method
        Set<String> keySet = map.keySet();

        for (String key : keySet) {
            String value = map.get(key);
            System.out.println(key + "," + value);
        }

    }
}

Output results:

Yang Guo, Xiao Longnv
Guo Jing, Huang Rong
Zhang Wuji, Zhao Min

          The second method is to use the entrySet() method to get all the key value pairs in the set, and then get the corresponding key or value.

HashMap set traversal method 2: key value pair set finding key value pair

  Step analysis
    - Gets a collection of all key value pair objects
          - Set < map. Entry < K, V > > entryset(): get the set of all key value pair objects
    - Traverse the collection of key value pair objects to get each key value pair object
          - Use the enhanced for implementation to get each Map.Entry
    - Get keys and values for objects based on key values
          - Get the key with getKey()
          - Get the value with getValue()

code implementation

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

/*
    Map Traversal of collection (mode 2):
        1:Gets a collection of all key value pair objects
            Set<Map.Entry<K,V>> entrySet(): Gets a collection of all key value pair objects
        2:Traverse the collection of key value pair objects to get each key value pair object
            Use the enhanced for implementation to get each Map.Entry
        3:Get keys and values for objects based on key values
            Get the key with getKey()
            Get the value with getValue()
 */
public class MapDemo02 {
    public static void main(String[] args) {
        //Create collection object
        Map<String, String> map = new HashMap<String, String>();

        //Add element
        map.put("zhang wuji", "Zhao Min");
        map.put("Guo Jing", "Huang Rong");
        map.put("Guo Yang", "little dragon maiden");

        //1: Gets a collection of all key value pair objects
        Set<Map.Entry<String, String>> me = map.entrySet();

//        Traverse the collection of key value pair objects to get each key value pair object
        for (Map.Entry<String, String> e : me) {
            String key = e.getKey();
            String value = e.getValue();
            System.out.println(key + "," + value);
        }

    }
}

  Output results:

Yang Guo, Xiao Longnv
Guo Jing, Huang Rong
Zhang Wuji, Zhao Min

          Both traversal methods are very practical. You can use whichever you are willing to use in development.

5, Comprehensive case of HashMap set

        There is a saying: it is better to retreat and form a net than to admire fish. After reading so many theoretical things, if you don't practice by yourself, the fish will always be in the fish pond and the knowledge will always be in the computer. Next, let's work on a problem together to deepen our impression.

        Case requirements:

Case requirements
    - Enter a string on the keyboard and count the number of occurrences of each string in the string.
    - For example, enter "aababcabcdcabcde" on the keyboard   Output on the console: "a(5)b(4)c(3)d(2)e(1)"

Train of thought analysis:

1: Enter a string on the keyboard
2: Create a HashMap collection with the key Character and the value Integer
3: Traverse the string to get each character
4: Take each character as a key to find the corresponding value in the HashMap collection and see its return value
    If the return value is null: it indicates that the character does not exist in the HashMap collection, the character is stored as a key and 1 as a value
    If the return value is not null: it indicates that the character exists in the HashMap collection, add 1 to the value, and then re store the character and the corresponding value
5: Traverse the HashMap set, get the keys and values, and splice them as required
6: Output results

  Code example:

        

import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

/*
    Requirements:
        Enter a string on the keyboard and count the number of occurrences of each string in the string.
        For example, enter "aababcabcdcabcde" on the keyboard 	 Output on the console: "a(5)b(4)c(3)d(2)e(1)"

    Idea:
        1:Enter a string on the keyboard
        2:Create a HashMap collection with the key Character and the value Integer
        3:Traverse the string to get each character
        4:Take each character as a key to find the corresponding value in the HashMap collection and see its return value
            If the return value is null: it indicates that the character does not exist in the HashMap collection, the character is stored as a key and 1 as a value
            If the return value is not null: it indicates that the character exists in the HashMap collection, add 1 to the value, and then re store the character and the corresponding value
        5:Traverse the HashMap set, get the keys and values, and splice them as required
        6:Output results
 */
public class HashMapDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String s = sc.nextLine();

        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();

        for (int i = 0; i < s.length(); i++) {
            char key = s.charAt(i);

            Integer value = hm.get(key);
            if (value == null) {
                hm.put(key, 1);

            } else {
                value++;
                hm.put(key, value);
            }
        }

        StringBuilder sb = new StringBuilder();

        Set<Character> keySet = hm.keySet();
        for (Character key1 : keySet) {
            Integer values = hm.get(key1);
            sb.append(key1).append("(").append(values).append(")");
        }
        String result = sb.toString();
        System.out.println(result);
    }
}

Output results:

  Please enter a string:
aababcabcdabcde
a(5)b(4)c(3)d(2)e(1)

6, Summary

          Learning a collection should carefully understand its unique methods and pay attention to differentiation. Only through more practice can we deepen our understanding of its usage, and we should understand it in combination with the knowledge we have learned before. There may be unexpected gains. The sharing of this issue is over here. It's better to eat it in combination with the previous issue. See you in the next issue!

Posted by cronus on Tue, 19 Oct 2021 17:32:33 -0700