Java - Collection - Map interface - collection summary

Characteristics of Map interface implementation class [very practical]

Note: This is about the Map interface features of JDK8

  1. Map and Collection exist side by side. Used to save data with mapping relationship: Key - Value (double column element)
  2. The key and value in the Map can be data of any reference type and will be encapsulated in the HashMap$Node object
  3. The Key in the Map cannot be repeated for the same reason as the HashSet. The source code has been analyzed earlier
  4. The value in the Map can be repeated
  5. The key and value of Map can be null. Note that there can be only one key and multiple values.
  6. String class is often used as the key of Map (other types can also be used - > object)
  7. There is a one-way one-to-one relationship between key and value, that is, the corresponding value can always be found through the specified key

package com.taotao.map_;

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

/**
 * Create By Liu Hongtao
 * 2022/1/8 16:34
 */
public class Map_ {
    public static void main(String[] args) {
//        Interpret the characteristics of the Map interface implementation class and use the implementation class HashMap
//        1. Map and Collection exist side by side. Used to save data with mapping relationship: Key - Value (double column element) (unordered)
        Map map = new HashMap();
        map.put("no1","Taotao");        //key - value key pair
        map.put("no2","zhang wuji");       //key - value


//        2. The key and value in the map can be data of any reference type and will be encapsulated in the HashMap$Node object
//        3. The Key in the map cannot be repeated for the same reason as the HashSet. The source code has been analyzed earlier
        map.put("no1","Zhang Sanfeng");
        System.out.println(map);        //When there is the same key, it will be replaced. Zhang Wuji, Zhang Sanfeng

//        4. The value in the map can be repeated
        map.put("no3","Zhang Sanfeng");
        System.out.println(map);

//        5. The key and value of map can be null. Note that there can be only one key and multiple values.
        map.put("null","null");
        map.put("no4","Little plum");
        System.out.println(map);        //Zhang Wuji, Zhang Sanfeng, Zhang Sanfeng, little plum

//        6. String class is often used as the key of Map
        map.clear();
        map.put(1,5);                   //ok
        System.out.println(map);        //1 = 5

//        7. There is a one-way one-to-one relationship between key and value, that is, the corresponding value can always be found through the specified key
        //Pass in a key through the get method and the corresponding value will be returned
        map.put("no5","Liu Hongtao");
        System.out.println(map.get("no5"));     //Liu Hongtao

    }
}

  1. The key - value diagram of Map storing data. A pair of key - values are placed in a Node. Because the Node implements the Entry interface, some books say that a pair of k - v is an Entry

package com.taotao.map_;

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

/**
 * Create By Liu Hongtao
 * 2022/1/8 17:17
 */
public class MapSource_ {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("no1","Taotao");;   //k-v
        map.put("no2","zhang wuji");    //k-v

        //unscramble
        //1.k - v finally HashMap$Node node = newNode(hash, key, value, null)
        //2.k - v in order to facilitate the programmer's traversal, an EntrySet collection is also created, which stores the type of element Entry and an Entry object
        //          k, V entryset < entry < k, V > >
        //3. In the entryset, the defined type is map Entry, but the HashMap$Node is actually stored
        //      This is because HashMap $node implements map Entry
        //4. When the HashMap$Node object is stored in the entrySet, it is convenient for us to traverse, because the map Entry provides two important methods
        //              1.getKey()  2.getValue
        Set set = map.entrySet();
        System.out.println(set.getClass());     //HashMap$EntrySet
        for (Object obj: set){
//            System.out.println(obj);          //no2 = Zhang Wuji, no1 = Taotao
//            System.out.println(obj.getClass());   //HashMap$Node

            //1. Make a downward transformation first
            Map.Entry entry = (Map.Entry) obj;
            System.out.println(entry.getKey() + "-" + entry.getValue());

        }

        Set set1 = map.keySet();
        System.out.println(set1.getClass());
        Collection values = map.values();
        System.out.println(values.getClass());      //Operation type
    }
}

  • Inheritance diagram of Map system

Map interface and common methods

  1. put: add
  2. remove: deletes the mapping relationship based on the key
  3. Get: get value according to key
  4. size: get the number of elements
  5. isEmpty: judge whether it is an empty set
  6. Clear: clear
  7. containsKey: check whether the key exists
package com.taotao.map_;

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

/**
 * Create By Liu Hongtao
 * 2022/1/8 18:21
 */
public class MapMethod {
    public static void main(String[] args) {
        Map map = new HashMap();
//        1. put: add
        map.put("1","2");
        map.put("2","2");
        System.out.println(map);    //1 = 2;    //2 = 2

//        2. remove: delete the mapping relationship according to the key
        map.remove("1");
        System.out.println(map);    //2 = 2

//        3. get: get the value according to the key
        System.out.println(map.get("2"));   //2

//        4. size: get the number of elements
        System.out.println(map.size());     //1

//        5. isEmpty: judge whether it is an empty set
        System.out.println(map.isEmpty());  //false

//        6. clear: clear
//        map.clear();

//        7. containsKey: check whether the key exists
        System.out.println(map.containsKey("2"));   //true
        System.out.println(map.containsValue("2")); //true
    }
}

Map interface traversal mode

package com.taotao.map_;


import java.util.*;

/**
 * Create By Liu Hongtao
 * 2022/1/8 20:08
 */
public class MapMethod02 {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("Taotao","12");
        map.put("Xiao Ming","13");
        map.put("Xiao Zhang","12");
        //practice
        // Group 1: take out all keys first, and take out the corresponding Value through the Key
        Set set = map.keySet();

        //(1) Enhanced for
        System.out.println("----The first way----");
        for (Object key :set){
            System.out.println(key + "-" + map.get(key));   //Get the corresponding value through the key
        }

        //(2) Iterator
        System.out.println("----The second way----");
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            Object key = iterator.next();
            System.out.println(key + "-" + map.get(key));
        }

        //practice
        //Group 2: take out all value s

        Collection values = map.values();
        //(1) Enhanced for
        System.out.println("----The first way----");
        for (Object value:values){
            System.out.println(value);
        }

        //(2) Iterator
        System.out.println("----The second way----");
        Iterator iterator1 = values.iterator();
        while(iterator1.hasNext()){
            Object value = iterator1.next();
            System.out.println(value);
        }

        //practice
        //Group 3: get k - v through EntrySet
        //(1) Enhanced for
        System.out.println("----entrySet()----");
        Set set1 = map.entrySet();  //EntrySet<Entry<K,V>>
        for (Object entrySet:set1){
            //Convert entry to map Entry
            Map.Entry m = (Map.Entry) entrySet;
            System.out.println(m.getKey() + "-" + m.getValue());
        }
        //(2) Iterator
        System.out.println("----iterator ----");
        Iterator iterator2 = set1.iterator();
        while (iterator2.hasNext()){
            Object entrySet = iterator2.next();
            System.out.println(entrySet.getClass());    //HashMap$Node - Implementation - > map Entry(getKey,getValue);
            //Transition down map Entry
            Map.Entry entry = (Map.Entry) entrySet;      //

            System.out.println(entry.getKey() + "-" + entry.getValue());
        }
//        1. containsKey: check whether the key exists
//        2. keySet: get all keys
        System.out.println(map.keySet());   //Xiao Ming, Xiao Zhang, Tao Tao

//        3. entrySet: get all relationships
        System.out.println(map.entrySet()); //Xiao Ming = 13, Xiao Zhang = 12, Tao Tao = 12
//        4. values: get all values



    }
}

HashMap capacity expansion mechanism (red black tree)

HashMap is the same as HashSet capacity expansion mechanism, so I won't describe it any more

Hashtable class

Comparison between Hashtable and HashMap

editionThread safe (synchronous)efficiencyAllow null keys and null values
HashMap1.2unsafefastsure
Hashtable1.0securityslowmay not

Hashtable capacity expansion mechanism

Properties class

Basic introduction

  1. The Properties class inherits from the Hashtable class and implements the Map interface. It also uses a key value pair to save data (it cannot be null)
  2. Its usage features are similar to Hashtable
  3. Properties can also be used from XXX In the properties file, load the data into the properties class object, and read and modify it
  4. After work XXX The properties file is usually used as a configuration file. This knowledge point is illustrated in the IO flow. If you are interested, please read the article first

Proprties class basic methods

package com.taotao.map_;

import java.util.Map;
import java.util.Properties;

/**
 * Create By Liu Hongtao
 * 2022/1/9 17:11
 */
public class PropertiesMethod {
    public static void main(String[] args) {
        Map map = new Properties();
        map.put("1","2");
        map.put("2","3");

        //Obtain the corresponding value through k
        System.out.println(map.get("1"));       //2

        //delete
        map.remove("1");
        System.out.println(map);                //{2=3}

        //modify
        map.put("2","4");
        System.out.println(map);                //{2=4}
    }
}

How to select collection implementation classes in development (practical experience)

  • In development, what set implementation class is selected mainly depends on the characteristics of business operations, and then selected according to the characteristics of set implementation class. The analysis is as follows
  1. First determine the type of storage (a group of objects [single column] or a group of key value pairs [double column])

  2. A group of objects [single column]: Collection interface

    Allow duplicates: List

    Add / delete: LinkedList [a two-way linked list is maintained at the bottom]

    Change query: ArrayList [maintain variable array of Object type at the bottom]

    Duplicate not allowed: Set

    Unordered: HashSet [the bottom layer is HashMap, which maintains a hash table (array + linked list + red black tree)]

    Sorting: TreeSet

    The insertion and extraction sequence is the same: LinkedHashSet [the bottom layer is LinkedHashMap, and the bottom layer is HashMap (core)], maintaining array + two-way linked list

  3. A set of key value pairs [double column]: Map

    1. Key disorder: HashMap [bottom layer: hash table jdk7: prime group + linked list, jdk8: array + linked list + red black tree]
    2. Key sorting: TreeMap
    3. The order of key insertion and extraction is the same: LinkedHashMap
    4. Read file: Properties

Keywords: Java Back-end

Added by jay_bo on Sun, 09 Jan 2022 13:15:48 +0200