• In a Collection, the elements are isolated (understood as single), and the elements stored in the Collection are stored element by element.
  • In a Map, elements exist in pairs (understood as husband and wife). Each element is composed of a key and a value, through which you can find the corresponding value.
  • A Collection in a Collection is called a single-column Collection, and a Collection in a Map is called a two-column Collection.
  • Note that collections in a Map cannot contain duplicate keys, and values can be repeated; Each key can only correspond to one value.

1 Common subclasses of Map Common subclasses of Map include:

  • HashMap

    : hash table structure used to store data. The access order of elements is not guaranteed to be consistent. To ensure that the keys are unique and not duplicated, we need to override the hashCode() and equals() methods of the keys.
    ,v>
  • LinkedHashMap

    : There is a subclass of LinkedHashMap under HashMap, which stores data in a hash table structure + linked list structure. The access order of elements can be guaranteed by the structure of linked list. The hash table structure ensures that the keys are unique and not duplicated. You need to override the hashCode() and equals() methods of the keys.
    ,v>

2 Common methods in Map interfaces

The Map interface defines a number of methods. The following are commonly used:

  • Public V PUT (K key, V value): Adds the specified key and value to the Map collection.
  • Public V remove(Object key): deletes the key pair corresponding to the specified key from the Map and returns the value of the deleted element.
  • Public V get(Object key) Obtains the corresponding value in the Map based on the specified key.
  • Boolean containsKey(Object key) Determines whether the collection contains the specified key.
  • Public Set

    keySet(): Gets all the keys in the Map Set and stores them in the Set.
  • Public Set< map.entry

    > entrySet(): A Set of all key-value pairs in the Map Set(Set Set).
    ,v>

The code runs as follows:

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

public class Demo01Map {
    public static void main(String[] args) {
        show01();
        show02();
        show03();
        show04();
    }

    private static void show04() {
        Map<String,Integer> map = new HashMap<>();
        map.put("Zhao Liying", 168); map.put("Angelababy", 165); map.put("Lin Chi-ling", 178); Integer v1 = map.get("Angelababy");

        boolean b1 = map.containsKey("Zhao Liying");
        System.out.println("========show04=========");
        System.out.println("b1:" + b1);

        boolean b2 = map.containsKey("Zhao Wu");
        System.out.println("b2:"+b2);
    }

    private static void show03() {
        Map<String,Integer> map = new HashMap<>();
        map.put("Zhao Liying", 168); map.put("Angelababy", 165); map.put("Lin Chi-ling", 178); Integer v1 = map.get("Angelababy");
        System.out.println("=======show03==========");
        System.out.println("v1:"+v1);

        Integer v2 = map.get("Dilieba");
        System.out.println("v2: "+v2);
    }

    private static void show02Map<String, Integer> map = new HashMap<>(); map.put("Zhao Liying", 168); map.put("Angelababy", 165); map.put("Lin Chi-ling", 178); System.out.println("=======show02==========");
        System.out.println(map);

        Integer v1 = map.remove("Lin Chi-ling");
        System.out.println("v1:"+v1);
        System.out.println(map);

        Integer v2 = map.remove("Lin Zhiying");
        System.out.println("v2:"+v2);
        System.out.println("= = = = = = = = = = = = = = = =");
    }

    private static void show01() {
        Map<String, String> map = new HashMap<>();
        System.out.println("======show01===========");
        String v1 = map.put("李晨"."Fan Bingbing 1");
        System.out.println("v1:"+v1);
        System.out.println(map);

        String v2 = map.put("李晨"."Fan Bingbing 2");
        System.out.println("v2:"+v2);
        System.out.println(map);

        map.put("Hit"."Long Xiaoyun");
        map.put("Yang guo"."Little Dragon Lady");
        map.put("Yin Zhiping"."Little Dragon Lady"); System.out.println(map); }}Copy the code

The running results are shown as follows:

     

3 Key search mode of Map collection

Key search: Obtains the value of the key based on the key in the element

Analysis steps:

1. Retrieve all keys in the Map. Since keys are unique, return a Set to store all keys.

Keyset () iterates through the Set of keys to get each key.

3. Obtain the value of the key based on the key. Get (K key)

Ergodic diagram:



The code runs as follows:

package Demo01; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; Set<K> keySet() returns the Set view of the keys contained in the Map. Implementation steps: 1. Use the method keySet() in the Map Set to extract all the keys from the Map Set and store them in a Set 2. traversesetPublic class Demo02KeySet {public static void main(String[]) {public static void main(String[]) {public static void main(String[]) Map<String, Integer> Map = new HashMap<>(); map.put("Zhao Liying", 168); map.put("Angelababy", 165); map.put("Lin Chi-ling", 178); Set<String> Set<String> Set<String>set= map.keySet(); / / 2. TraversalsetIterator<String> it = set.iterator(); Iterator<String> it = set.iterator();while(it.hasNext()){ String key = it.next(); Integer value = map.get(key); //3. Find the value system.out.println (key +) by using the Map method get(key)"-- >"+value);
        }
        System.out.println("= = = = = = = = = = = = = = = = ="); // Use enhancementsforIterate over the Set Setfor (String key :
                set) {
            Integer value = map.get(key);
            System.out.println(key+"- >"+value);
        }
        System.out.println("= = = = = = = = = = = = = = = = = = =");
        for(String key : map.keySet()) { //3. Value Integer Value = map.get(key); System.out.println(key+"-- >"+value); }}}Copy the code

The running results are shown as follows:

                                    

3.1 Entry Key-value pair objects





Since Entry represents a pair of keys and values, it also provides a way to get the corresponding key and corresponding value:

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

The Map collection also provides methods to get all Entry objects:

  • Public Set< map.entry

    > entrySet(): A Set of all key-value pairs in the Map Set(Set Set).
    ,v>

4 Map Traversal mode of key/value pairs

Key-value pair mode: Obtains the keys and values in each Entry object in the collection.

Operation steps and diagrams:

1. Obtain all Entry pairs in the Map Set and return them as sets. Method tip :entrySet().

2. Iterate through the Set Set containing Entry objects to obtain each Entry object.

3. Obtain the keys and values in the Entry object. Getkey () getValue()



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

The code runs as follows:

package Demo01; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; Entry<K,V>> entrySet() returns a Set view of the mapping relationships contained in this Map. Implementation steps: 1. Use entrySet() in the Map Set to extract multiple Entry objects from the Map Set and store them in a Set 2. 3. Use the getKey() and getValue() methods in the Entry object to obtain keys and values */ public class Demo03EntrySet {public static void Main (String[] args) {// Create a Map collection object Map<String, Integer> Map = new HashMap<>(); map.put("Zhao Liying", 168); map.put("Angelababy", 165); map.put("Lin Chi-ling", 178); EntrySet () : entrySet() : entrySet() : entrySet < map.entry <String,Integer>>set= map.entrySet(); Iterator< map.entry <String, Integer>> it = set.iterator(); Iterator< map.entry <String, Integer>> it = set.iterator();while(it.hasNext()){ Map.Entry<String , Integer> entry = it.next(); String key = entry.getKey(); String key = entry.getkey (); //3. Integer value = entry.getValue(); System.out.println(key+"- >"+value);
        }
        System.out.println("= = = = = = = = = = = = = = = = = = = = = = = =");
        for (Map.Entry<String, Integer> entry:setString key = entry.getKey(); String key = entry.getkey (); Integer value = entry.getValue(); System.out.println(key+"-- >"+value); }}}Copy the code

The running results are shown as follows:

                                         

5 HashMap Stores user-defined key values

  • When storing custom objects in a HashMap, if the custom object exists as a key, then to ensure that the object is unique, you must override the object’s hashCode and equals methods (if you forget, recall that HashSet holds custom objects).
  • To ensure that the keys stored in the map are retrieved in the same order, you can use the java.util.LinkedHashMap collection to store them.

The code runs as follows:

package Demo02; import java.util.HashMap; import java.util.Map; import java.util.Set; /* The HashMap stores the Map collection of custom types of key values. The key is guaranteed to be unique: the element that is the key must be overriddenhashPublic class Demo01HashMapSavePerson {public static void main(String[] args) {show01(); show02(); } /* HashMap stores custom type key values. Key :String Type String class rewritehashThe Code and equals methods ensure that key values are unique :Person values can be repeated (people of the same name and age are treated as the same) */ private static voidshow01() {// create HashMap<String,Person> map = new HashMap<>(); // Add element map.put("Beijing",new Person("Zhang", 18)); map.put("Shanghai",new Person("Bill", 19)); map.put("Guangzhou",new Person("Fifty", 20)); map.put("Beijing",new Person("Daisy", 18)); // Add elements to Set<String>set = map.keySet();
        for (String key :
                set) {
            Person value = map.get(key);
            System.out.println(key+"-- >"+value);
        }
        System.out.println("= = = = = = = = = = = = = = = = = ="); } /* The Person class would have to be overriddenhashCode and equals methods to ensure that the key is unique value:String can be repeated */ private static voidshow02(){// create a HashMap collection HashMap<Person, String> map = new HashMap<>(); // Add the element map.put(new Person("The queen", 18),"British");
        map.put(new Person(The First Emperor of Qin, 18),"Qin");
        map.put(new Person("Vladimir putin", 38),"Russia");
        map.put(new Person("The queen", 18),"Mauritius"); // Use entrySet and enhancementforSet< map. Entry<Person,String >>set = map.entrySet();
        for (Map.Entry<Person, String> entry:set
                ){
            Person key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"= = = >"+value);
        }
    }
}
import java.util.Objects;

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

    public Person() {

    }

    public Person(String name, int age) {

        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() ! = o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, 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; }}Copy the code

The running results are shown as follows:



5.1 LinkedHashMap

Under HashMap there is a subclass LinkedHashMap, which is a data storage structure that combines linked lists and hash tables to ensure order.

The code runs as follows:

package Demo03; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /* Java.util. LinkedHashMap<K,V> Entends HashMap<K,V> Map interface hash table and link list implementation, with predictable iteration order. Underlying principles: Public class Demo02LinkedHashMap {public static void main(String[] args) {HashMap<String, String> map = new HashMap<>(); map.put("a"."a");
        map.put("c"."c");
        map.put("b"."b");
        map.put("a"."b");
        System.out.println(map);
        System.out.println("= = = = = = = = = = = = = = = = = = =");
        LinkedHashMap<String, String> linked = new LinkedHashMap<>();
        linked.put("a"."a");
        linked.put("c"."c");
        linked.put("b"."b");
        linked.put("a"."b");
        System.out.println(linked);
        System.out.println("= = = = = = = = = = = = = = = = = = =");
        LinkedHashMap<String, String> map1 = new LinkedHashMap<String, String>();
        map1.put("Deng chao"."Grandson couple");
        map1.put("李晨"."Fan Bingbing");
        map1.put("Andy Lau".Carol Chu);
        Set<Map.Entry<String, String>> entrySet = map1.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            System.out.println(entry.getKey() + ""+ entry.getValue()); }}}Copy the code

The running results are shown as follows: