Summary of Map set in java

  • In the Collection, the elements are isolated (understood as single), and the elements are stored in the Collection one by one.
  • In Map, the elements are in pairs (understood as husband and wife). Each element consists of two parts: key and value, through which the corresponding value can be found.
  • A Collection in a Collection is called a single column Collection, and a Collection in a Map is called a double column Collection.
  • It should be noted that the set in the Map cannot contain duplicate keys, and the values can be repeated; each key can only correspond to one value.

1 common subclass of map

Common subclasses of Map include:

  • HashMap < K, V >: the hash table structure used to store data. The access order of elements cannot be consistent. To ensure the uniqueness and non repetition of the key, the hashCode() method and the equals() method of the key need to be rewritten.
  • LinkedHashMap < K, V >: there is a subclass LinkedHashMap under the HashMap, and the hash table structure + linked table structure is used to store data. The access order of elements can be ensured to be consistent through the chain list structure; the key can be guaranteed to be unique and not repeated through the hash table structure, and the hashCode() method and equals() method of the key need to be rewritten.

2 common methods in map interface

There are many methods defined in the Map interface. The common methods are as follows:

  • public V put(K key, V value): adds the specified key and the specified 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 the specified key is included in the collection.
  • Public Set < k > keyset(): get all the keys in the Map Set and store them in the Set set.
  • public Set< Map.Entry < K, V > > entryset(): get the set of all key value pairs in the map set.

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("Yang Ying",165);
        map.put("Lin Zhiling",178);
        Integer v1 = map.get("Yang Ying");

        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("Yang Ying",165);
        map.put("Lin Zhiling",178);
        Integer v1 = map.get("Yang Ying");
        System.out.println("=======show03==========");
        System.out.println("v1:"+v1);

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

    private static void show02() {
        //Create map collection object
        Map<String, Integer> map = new HashMap<>();
        map.put("Zhao Liying",168);
        map.put("Yang Ying",165);
        map.put("Lin Zhiling",178);
        System.out.println("=======show02==========");
        System.out.println(map);

        Integer v1 = map.remove("Lin Zhiling");
        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("Li Chen","Fan Bingbing 1");
        System.out.println("v1:"+v1);
        System.out.println(map);

        String v2 = map.put("Li Chen","Fan Bingbing 2");
        System.out.println("v2:"+v2);
        System.out.println(map);

        map.put("Cold peak","Long Xiaoyun");
        map.put("Yang Guo","little dragon maiden");
        map.put("Yin Zhiping","little dragon maiden");
        System.out.println(map);
    }
}

The operation results are as follows:

3 search method of map set traversal key

Key value finding method: that is, obtain the value corresponding to the key through the key in the element

Analysis steps:

1. Get all the keys in the Map. Since the keys are unique, a Set collection is returned to store all the keys. Method tip: keyset()
2. Traverse the Set set of keys to get each key.
3. Get the value corresponding to the key according to the key. Method tip: get(K key)

Traversal diagram:

The code runs as follows:

package Demo01;

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

/*
    Map The first way to traverse a collection: by searching for values through keys
    Map Methods in collection:
         Set<K> keySet() Returns the Set view of the key contained in this map.
    Implementation steps:
        1.Use the method keySet() in the Map Set to retrieve all the keys in the Map Set and store them in a Set set
        2.Traverse the set set to get every key in the Map set
        3.get(key) through the method in the Map set, and find value through key
 */
public class Demo02KeySet {
    public static void main(String[] args) {
        //Create Map collection object
        Map<String, Integer> map = new HashMap<>();
        map.put("Zhao Liying",168);
        map.put("Yang Ying",165);
        map.put("Lin Zhiling",178);

        //1. Use the method keySet() in the Map Set to retrieve all the keys in the Map Set and store them in a Set set
        Set<String> set = map.keySet();

        //2. Traverse the set set to obtain each key in the Map set
        //Traversing Set sets with iterators
        Iterator<String> it = set.iterator();
        while (it.hasNext()){
            String key = it.next();
            Integer value = map.get(key);
            //3. get(key) through the method in the Map set, and find value through the key
            System.out.println(key +"-->"+value);
        }
        System.out.println("=================");
        //Traversing Set sets with enhanced for
        for (String key :
                set) {
            Integer value = map.get(key);
            System.out.println(key+"--->"+value);
        }
        System.out.println("===================");
        for (String key :
                map.keySet()) { //3. get(key) through the method in the Map set, and find value through the key
            Integer value = map.get(key);
            System.out.println(key+"-->"+value);

        }
    }
}

The operation results are as follows:

3.1 Entry key value to object

There are two kinds of objects stored in the Map, one is called key, the other is called value. They are one-to-one correspondence in the Map. This pair of objects is also called an entry in the Map. Entry encapsulates the corresponding relationship of key value pairs into objects. That is, key value pair object, so when we traverse the Map collection, we can get the corresponding key and corresponding value from each key value pair object.

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

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

Methods for getting all Entry objects are also provided in the Map collection:

  • public Set< Map.Entry < K, V > > entryset(): get the set of all key value pairs in the map set.

4 Map set traversal key value pair mode

Key value pair method: that is, through each key value pair (Entry) object in the collection, get the key and value in the key value pair (Entry) object.

Operation steps and diagrams:

1. Get all the key value pair (Entry) objects in the Map collection and return them in the form of Set collection. Method tip: entrySet().
2. Traverse the Set set containing the key value pair (Entry) object to get each key value pair (Entry) object.
3. Obtain the key and value in the Entry object through the key value pair (Entry) object. Method tip: getkey() getValue()

Note: Map sets cannot be traversed directly using iterators or foreach. But it can be used after being converted to Set.

The code runs as follows:

package Demo01;

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

/*
    Map The second way of collection traversal: using Entry object traversal

    Map Methods in collection:
        Set<Map.Entry<K,V>> entrySet() Returns the Set view of the mapping relationships contained in this mapping.

    Implementation steps:
        1.Use the method entrySet() in the Map collection to take out multiple Entry objects in the Map collection and store them in a Set collection
        2.Traverse the Set set to get each Entry object
        3.Use the methods getKey() and getValue() in the Entry object to get the key and value
 */
public class Demo03EntrySet {
    public static void main(String[] args) {
        //Create Map collection object
        Map<String, Integer> map = new HashMap<>();
        map.put("Zhao Liying",168);
        map.put("Yang Ying",165);
        map.put("Lin Zhiling",178);

        //1. Use the method entrySet() in the Map Set to take out multiple Entry objects in the Map Set and store them in a Set set Set
        Set<Map.Entry<String,Integer>> set = map.entrySet();

        //2. Traverse the Set set to get each Entry object
        //Traversing Set sets with iterators
        Iterator<Map.Entry<String , Integer>> it = set.iterator();
        while(it.hasNext()){
            Map.Entry<String , Integer> entry = it.next();
            //3. Use the methods getKey() and getValue() in the Entry object to get the key and value
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key+"--->"+value);
        }
        System.out.println("========================");
        for (Map.Entry<String, Integer> entry:set
        ){//3. Use the methods getKey() and getValue() in the Entry object to get the key and value
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key+"-->"+value);
        }
    }
}

The operation results are as follows:

5 HashMap stores custom type key values

  • When storing a custom object in a HashMap, if the custom object exists as a key, the hashCode and equals methods of the object must be copied to ensure that the object is unique (if you forget, please review the HashSet to store the custom object).
  • If you want to ensure that the key stored in the map is consistent with the order of retrieval, you can use the java.util.LinkedHashMap Assemble to store.

The code runs as follows:

package Demo02;

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

/*
    HashMap Store custom type key values
    Map The set guarantees that the key is unique:
        As the key element, the hashCode method and the equals method must be overridden to ensure that the key is unique
 */
public class Demo01HashMapSavePerson {
    public static void main(String[] args) {
       show01();
       show02();

    }
    /*
           HashMap Store custom type key values
           key:String type
               String Class rewrites the hashCode method and equals method to ensure that the key is unique
           value:Person type
               value It can be repeated (people of the same age are regarded as the same)
        */
    private static void show01() {
        //Create a HashMap collection
        HashMap<String,Person> map = new HashMap<>();
        //Add elements to the collection
        map.put("Beijing",new Person("Zhang San",18));
        map.put("Shanghai",new Person("Li Si",19));
        map.put("Guangzhou",new Person("Wang Wu",20));
        map.put("Beijing",new Person("Zhao Liu",18));
        //Add elements to the collection
        Set<String> set = map.keySet();
        for (String key :
                set) {
            Person value = map.get(key);
            System.out.println(key+"-->"+value);
        }
        System.out.println("==================");
    }

    /*
        HashMap Store custom type key values
        key:Person type
            Person Class must override the hashCode method and the equals method to ensure that the key is unique
        value:String type
            Repeatable
     */
    private static void show02(){
        //Create a HashMap collection
        HashMap<Person, String> map = new HashMap<>();
        //Add elements to the collection
        map.put(new Person("queen",18),"britain");
        map.put(new Person("First Emperor of Qin",18),"the Qin state");
        map.put(new Person("Vladimir Putin",38),"Russia");
        map.put(new Person("queen",18),"mauritius");
        //Traversing Map sets with entrySet and enhanced for
        Set<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;
    }
}

The operation results are as follows:

5.1 LinkedHashMap

Under the HashMap, there is a subclass LinkedHashMap, which is a data storage structure composed of linked list and hash table, which can 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 Implementation of hash table and link list of interface, with predictable iteration order.
    Underlying principle:
        Hash table + linked list (order of record elements)
 */
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", "Sun Li");
        map1.put("Li Chen", "Fan Bingbing");
        map1.put("Lau Andy", "Carol ");
        Set<Map.Entry<String, String>> entrySet = map1.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            System.out.println(entry.getKey() + "  " + entry.getValue());
        }

    }
}

The operation results are as follows:

Tags: Java

Posted on Wed, 24 Jun 2020 04:06:53 -0400 by droomagon