Map set system

1, Overview of Map collections

Map collection overview and usage

● Map set is a double column set, and each element contains two data.

● format of each element in the Map set: key=value (key value pair element).

● the Map set is called "key value pair set".

 

Overall format of Map collection

● format of Collection set: [element 1, element 2, element 3,...]

● complete format of Map set: {key1=value, key2=value2, key3=value3,...}

One of the usage scenarios of Map collection: shopping cart system

analysis

● the four items provided by the shopping cart and the quantity purchased need to be stored in containers in the background.

● each commodity object corresponds to a quantity one by one.

● regard the commodity object as the key of the Map set, and the purchase quantity can be called the value of the Map set.

{commodity 1 = 2, commodity 2 = 3, commodity 3 = 2, commodity 4 = 3}

 

Summary:

What is a Map collection? What is the usage scenario like?

● Map set is the set of key value pairs

● Map collection is very suitable for business scenarios such as shopping carts

 

2, Characteristics of Map set system

Map set system

 

explain

● the most used Map set is HashMap.

● focus on mastering HashMap, LinkedHashMap and TreeMap.

 

Characteristics of Map set system

● the characteristics of Map sets are determined by keys.

● the establishment of Map set is out of order, without repetition, without index, and the value is not required (can be repeated).

● the value corresponding to the repeated key behind the Map set will overwrite the value of the previous repeated key.

● key value pairs of Map set can be null.

 

Features of Map collection implementation class

● HashMap: out of order, no repetition, no index and no requirement for value. (consistent with Map system)

● LikedHashMap: orderly, non repetitive, no index, no value requirements.

● TreeMap: sorting, no repetition, no index, no requirement for value.

[code example]

/**
 * Objective: to understand the Map feature system: disordered keys, no repetition, no index and no requirements for values
 */
public class MapDemo1 {
    public static void main(String[] args){
        //1. Create a Map collection object
        Map<String, Integer> maps = new HashMap<>();
        maps.put("Erke",3);
        maps.put("Java",2);
        maps.put("Chinese wolfberry",100);
        maps.put("Anta",4);
        maps.put("Java",77); //Overwrite previous data
        maps.put(null,null);
        System.out.println(maps);

        Map<String, Integer> maps1 = new LinkedHashMap<>();
        maps1.put("Erke",3);
        maps1.put("Java",2);
        maps1.put("Chinese wolfberry",100);
        maps1.put("Anta",4);
        maps1.put("Java",77); //Overwrite previous data
        maps1.put(null,null);
        System.out.println(maps1);
    }
}

Operation results:

{null=null, Java=77, Chinese wolfberry=100, Erke=3, Anta=4}
{Erke=3, Chinese wolfberry=100, Java=77, Anta=4, null=null}

 

3, Common API for Map collection

Map collection

● Map is the ancestral interface of double column set, and its function is that all double column sets can be inherited and used.

 

The Map API is as follows

Method name explain
V put(K key, V value) Add element
V remove(Object key) Delete key value pair elements according to key
void clear( ) Remove all key value pair elements
boolean containsKey(Object key) Determines whether the collection contains the specified key
boolean containsValue(Object value) Determines whether the collection contains the specified value
boolean isEmpty( ) Determine whether the collection is empty
int size( ) The length of the set, that is, the number of pairs in the set

[code example 1] add element

public class MapDemo {
    public static void main(String[] args) {
        // 1. Add elements: unordered, non repetitive, and no index
        Map<String, Integer> maps = new HashMap<>();
        maps.put("iphone",10);
        maps.put("doll",20);
        maps.put("iphone",100);
        maps.put("huawei",100);
        maps.put("articles for daily use",10);
        maps.put("Wrist watch",10);
        System.out.println(maps);
    }
}

Operation results:

{huawei=100, Wrist watch=10, articles for daily use=10, doll=20, iphone=100}

 

[code example 2] empty collection

maps.clear();
System.out.println(maps);   // {}

 

[code example 3] judge whether the collection is empty. If it is empty, return true, otherwise!

System.out.println(maps.isEmpty());  // false

 

[code example 4] obtain the corresponding value according to the key

Integer key = maps.get("huawei");
System.out.println(key); // 100
System.out.println(maps.get("articles for daily use")); // 10
System.out.println(maps.get("Daily necessities 2")); // null

 

[code example 5] delete the entire element according to the key. (deleting a key returns the value of the key)

System.out.println(maps.remove("iphone"));  // 100
System.out.println(maps);

  Operation results:

100
{huawei=100, Wrist watch=10, articles for daily use=10, doll=20}

 

[example code 6] judge whether a key is included, and return true if included, and vice versa!

System.out.println(maps.containsKey("doll")); // true
System.out.println(maps.containsKey("Doll 2")); // true
System.out.println(maps.containsKey("iphoneX")); // true

 

[example code 7] judge whether a value is included

System.out.println(maps.containsValue(100)); // true
System.out.println(maps.containsValue(10)); // true
System.out.println(maps.containsValue(22)); // false

 

[example code 8] get the set of all keys

// {huawei=100, watch = 10, daily necessities = 10, doll = 20, iphone=100}
// Get the set of all keys: public set < k > keyset < >
// The Set set is also unordered, non repetitive, and non indexed. The underlying principle is the same. So it can be collected by Set
Set<String> keys = maps.keySet();
System.out.println(keys);

 

[code example 9] get the set of all values

// Get the collection of all values: Collection < V > values();
Collection<Integer> values = maps.values();
System.out.println(values);  // [100, 10, 10, 20, 100]

 

[code example 10] set size

System.out.println(maps.size()); // 5

 

[code example 11] merge other sets

public class MapDemo {
    public static void main(String[] args) {
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("Java1",1);
        map1.put("Java2",100);
        System.out.println(map1);

        Map<String, Integer> map2 = new HashMap<>();
        map2.put("Java2",1);
        map2.put("Java3",100);
        System.out.println(map2);
        System.out.println("-------After the merger, it is as follows:-------");

        map1.putAll(map2);
        System.out.println(map1);
        System.out.println(map2);
    }
}

Operation results:

{Java2=100, Java1=1}
{Java2=1, Java3=100}
-------After the merger, it is as follows:-------
{Java2=1, Java3=100, Java1=1}
{Java2=1, Java3=100}

 

4, Traversal method 1 of Map collection: key to find value

Traversal method 1 of Map collection: key to find value

● get all the keys of the Map Set first.

● traverse the Set set, and then extract the corresponding value through the key.

 

API involved in key value finding

Method name explain
Set<K> keySet( ) Gets a collection of all keys
V get(Object key) Get value according to key

 

[code example]

public class MapDemo01 {
    public static void main(String[] args){
        Map<String, Integer> maps = new HashMap();
        // 1. Add elements: unordered, non repetitive, and no index
        maps.put("doll",30);
        maps.put("iphone",100);
        maps.put("huawei",1000);
        maps.put("articles for daily use",10);
        maps.put("Wrist watch",10);

        // 1. Key value finding: Step 1: get all keys of the set first
        Set<String> keys = maps.keySet();
        System.out.println(keys);
        // 2. Step 2: traverse each key and extract the value according to the key
        for(String ele : keys){
             Integer value = maps.get(ele);
            System.out.println(ele + " ===> " + value);
        }
    }
}

Operation results:

[huawei, Wrist watch, articles for daily use, doll, iphone]
huawei ===> 1000
 Wrist watch ===> 10
 articles for daily use ===> 10
 doll ===> 30
iphone ===> 100

 

5, Traversal mode 2 of Map set: key value pair

● traversal mode 2 for traversing Map set: key value pair

● first convert the Map Set into a Set set. Each element in the Set is a key value pair entity type.

● traverse the Set, and then extract the keys and values.

 

API to which key value pairs are designed

Method name explain
Set<Map.Entry<K,V>> entrySet( ) Gets a collection of all key value pair objects
K getKey( ) Get key
V getValue( ) Get value

 

[code example]

public class MapDemo02 {
    public static void main(String[] args) {
        Map<String , Integer> maps = new HashMap<>();
        // 1. Add elements: out of order, no repetition, no index.
        maps.put("doll",30);
        maps.put("iphoneX",100);
        maps.put("huawei",1000);
        maps.put("articles for daily use",10);
        maps.put("Wrist watch",10);
        System.out.println(maps);
        // maps = {huawei=1000, watch = 10, daily necessities = 10, iphoneX=100, doll = 30}
        /**
         maps = {huawei=1000, Watch = 10, daily necessities = 10, iPhone x = 100, doll = 30}
         👇
         Use foreach to traverse the map set. It is found that the key value pair elements of the map set have no type directly. So you can't directly foreach through the collection.
         👇
         You can call the entrySet method of Map to convert the Map Set into the Set set form maps.entrySet();
         👇
         Set<Map.Entry<String,Integer>> entries =  maps.entrySet();
         [(huawei=1000), (Watch = 10), (daily necessities = 10), (iphoneX=100), (Doll = 30)]
         entry
         👇
         At this point, you can use foreach traversal
         */
        // 1. Convert Map Set to Set set Set
        Set<Map.Entry<String, Integer>> entries = maps.entrySet();
        // 2. Start traversal
        for(Map.Entry<String, Integer> entry : entries){
            String key = entry.getKey();
            int value = entry.getValue();
            System.out.println(key + "====>" + value);
        }
    }
}

Operation results:

{huawei=1000, Wrist watch=10, articles for daily use=10, iphoneX=100, doll=30}
huawei====>1000
 Wrist watch====>10
 articles for daily use====>10
iphoneX====>100
 doll====>30

 

6, Traversal method of Map collection: Lambda expression

Pending

 

 

 

7, Implementation class of Map collection HashMap

Map collection case - count the number of voters

demand

80 students in A class now need to form an autumn outing. The monitor provides four scenic spots in turn (A, B, C and D). Each student can only choose one scenic spot. Please count out which scenic spot wants to go the most.

analysis

● take the data selected by 80 students into the program.

Define a Map collection to store the results of the final statistics.

Traverse the data selected by 80 students to see whether it exists in the Map set. If it does not exist, it is stored in "data = 1", and if it exists, its corresponding value is + 1

[code example]

/**
   Demand: count the number of voters
 */
public class MapTest1 {
    public static void main(String[] args) {
         // 1. Bring in the data selected by 80 students.
        String[] selects = {"A" , "B", "C", "D"};
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < 80; i++) {
            sb.append(selects[r.nextInt(selects.length)]);
        }
        System.out.println(sb);

        // 2. Define a Map set to record the final statistical results: a = 30, B = 20, C = 20, d = 10. The key is the scenic spot value and the selected quantity
        Map<Character, Integer> infos = new HashMap<>(); //

        // 3. Traverse the data selected by 80 students
        for (int i = 0; i < sb.length(); i++) {
            // 4. Extract the currently selected character
            char ch = sb.charAt(i);
            // 5. Determine whether this key exists in the Map collection
            if(infos.containsKey(ch)){
                 // Let its value + 1
                infos.put(ch , infos.get(ch) + 1);
            }else {
                // It shows that this scenic spot is selected for the first time
                infos.put(ch , 1);
            }
        }

        // 4. Output set
        System.out.println(infos);

    }
}

 

The principle of implementing class HashMap with Map set

Features of HashMap

● HashMap is an implementation class in Map. The characteristics are determined by the key: disorder, non repetition and no index.

● there are no special methods to learn. You can directly use the methods in the Map

● the underlying principle of HashMap is the same as that of HashSet, which is a hash table structure, except that each element of HashMap contains two values.

In fact, the bottom layer of the Set series collection is implemented by Map, but the elements in the Set collection only need key data, not value data.

public HashSet(){
  map = new HashMap<>();
}

 

[code example]

Definition class: Student

Click to view the code
public class Student {
    private String name;
    private int age;
    private char sex;

    public Student() {
    }

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

    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;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    /**
       As long as the contents of the two objects are the same, the result must be true
     * @param o
     * @return
     */
    @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 && sex == student.sex && Objects.equals(name, student.name);
    }

    /**
     s1 = new Student("Intact ", 20, 'male')
     s2 = new Student("Intact ", 20, 'male')
     s3 = new Student("Zhou Xiong ", 21, 'male')
     */
    @Override
    public int hashCode() {
        return Objects.hash(name, age, sex);
    }

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

  Test class:

public class HashMapDemo1 {
    public static void main(String[] args) {
         // The Map collection removes duplicate elements according to the key
        Map<Student, String> maps = new HashMap<>();

        Student s1 = new Student("All right", 20, 'male');
        Student s2 = new Student("All right", 20, 'male');
        Student s3 = new Student("Zhou Xiong", 21, 'male');

        maps.put(s1, "Beijing");
        maps.put(s2, "Shanghai");
        maps.put(s3, "Guangzhou");

        System.out.println(maps);
    }
}

  Operation results:

{Student{name='All right', age=20, sex=male}=Shanghai, Student{name='Zhou Xiong', age=21, sex=male}=Guangzhou}

 

Summary:

Characteristics and underlying principles of HashMap

● determined by the key: unordered, non duplicate and no index. The bottom layer of HashMap is the hash table structure

● rely on hashCode method and equals method to ensure the uniqueness of keys.

● if the key is to store a custom object, you need to override the hashCode and equals methods.

● based on hash table. Good performance in addition, deletion, modification and query.

 

Posted by abalfazl on Wed, 24 Nov 2021 12:12:46 -0800