JavaSE advanced programming summary and training-summary of basic usage methods of collection 3 (Map interface)

Summary of the basic usage of the collection

Five, Map interface

Let me talk about some basic concepts:

Map stores key-value pairs (key-value), where: key is stored with Set! So, once we write a class ourselves, if we want it to be the key, we must rewrite the hashcode() and equals() methods! Then introduce the detailed classes that implement the Map interface:

5.1, HashMap collection

Let me talk about the knowledge about HashMap first:
① Similar to HashSet, the key and value of null are allowed.
② It is also the key-value pair indexed by the Hash value, so the access efficiency is very high, and the search efficiency is also very high (higher than the Tree implementation The time complexity of the constant!)
③ In HashMap, the condition for judging two keys is the same: first judge whether the hashcode() is the same, and then judge equals(), and the only condition to judge whether the value is the same is judge equals() Is true!

5.1.1. Let's first look at an example:

package MapInterface;

import java.util.*;

/**
 * @author jiangzl
 */
public class MyHashMap {
    
    
    public static void main(String[] args){
    
    
        HashMap myHashMap = new HashMap();
        myHashMap.put("stu1", 1);
        myHashMap.put("stu2", 2);
        myHashMap.put("stu3", 3);
        myHashMap.put("stu3", 4);
        myHashMap.put("stu4", 5);

        System.out.println("-----------第一种遍历HashMap的方法-----------");
        Set keySet = myHashMap.keySet();
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()){
    
    
            Object key = iterator.next();
            Object val = myHashMap.get(key);
            System.out.println("key = " + key + " , value = " + val);
        }

        System.out.println("-----------第二种遍历HashMap的方法-----------");
        Set entrySet = myHashMap.entrySet();
        iterator = entrySet.iterator();
        while (iterator.hasNext()){
    
    
            Map.Entry kv = (Map.Entry)iterator.next();
            Object k = kv.getKey();
            Object v = kv.getValue();
            System.out.println("key = " + k + " , value = " + v);
        }
    }
}

Take a look at the output of this example:
Insert picture description here

5.1.5. Explain this example:

First: About the access of HashMap:

The deposit uses the put(key, value); method, there are many ways to get it: if you know the key, you can use the get(key) method, and the value of value will be returned to you. But because HashMap allows the key and value to have nulls! So it's best to make an empty judgment before using the get(key) method!

Second: About the traversal of HashMap

Its traversal is really different from other collection interfaces! Because it has no iterators that can be manipulated directly! But we know that if we can traverse every key, we can get every key-value pair! Or to get each key-value pair, you can also get the key and value through the getkey() and getvalue() methods!

Method 1: Traverse each key: We can use: Set keySet = myHashMap.keySet();to get a Set object ( remember that it is not a HashSet object ) and after having this object, you can use iterators to traverse it!

Detailed example:

		Set keySet = myHashMap.keySet();
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()){
    
    
            Object key = iterator.next();
            Object val = myHashMap.get(key);
            System.out.println("key = " + key + " , value = " + val);
        }

Method 2: Traverse each key-value pair, use:, Set entrySet = myHashMap.entrySet();and then use getX() to get the key and value!

Detailed example:

		Set entrySet = myHashMap.entrySet();
        iterator = entrySet.iterator();
        while (iterator.hasNext()){
    
    
            Map.Entry kv = (Map.Entry)iterator.next();
            Object k = kv.getKey();
            Object v = kv.getValue();
            System.out.println("key = " + k + " , value = " + v);
        }
Two considerations:

First: There is a line of code worth noting: even when obtaining key-value pairs, a static method of Map: Entry() is required!

Second: If you don't know what data type the specific key and value are, it is best to use the Object class, and then operate according to polymorphism. Of course, it would be great if you can know the specific type!

Third: I forgot to mention this before, HashMap does not allow one key to be mapped to two values! So after two put operations on a key, only the one put last time will be kept!

5.1.6. Summary of several commonly used methods of Map:

1. Add function:
V put (K key, V value): add element.
If the key is stored for the first time, store the element directly, and return null.
If the key does not exist for the first time, replace the previous value with the value and return the previous value

2. Delete function:
void clear(): remove all key-value pair elements
V remove(Object key): delete key-value pair elements according to the key, and return the value

3. Judgment function:
boolean containsKey(Object key): judge whether the set contains the specified key
boolean containsValue(Object value): judge whether the set contains the specified value
boolean isEmpty(): judge whether the set is empty

4. Get function:
Set<Map.Entry<K,V>> entrySet():
V get(Object key): get the value according to the key
Set keySet(): get the collection of all keys in the collection
Collection values(): get the collection The set of all values ​​in

5. Length function:
int size(): returns the number of key-value pairs in the collection

5.3, LinkedHashMap collection

In fact, this is super simple, that is, the bottom layer is implemented by hash and linked list. What can be done is to maintain the iterative sequence of Map to ensure that what you input is what you output. Then the HashMap class is inherited, so the efficiency is also very high. The application scenario is also obvious, that is, when you require the input order and output order to be consistent, use this set, let's take a look at the code:

package MapInterface;

import java.util.*;

/**
 * @author jiangzl
 */
public class MyHashMap {
    
    
    public static void main(String[] args){
    
    
        LinkedHashMap myHashMap = new LinkedHashMap();
        myHashMap.put("stu1", 1);
        myHashMap.put("stu2", 2);
        myHashMap.put("stu3", 3);
        myHashMap.put("stu3", 4);
        myHashMap.put("stu4", 5);

        Set keySet = myHashMap.keySet();
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()){
    
    
            Object k = iterator.next();
            Object v = myHashMap.get(k);
            System.out.println("key = " + k + " , value = " + v);
        }
    }
}

Look at the output:

Insert picture description here
It's very simple, right? In fact, the output order is consistent with the input order, and then the efficiency is the same as HashMap.

5.2, TreeMap collection

This is no different from TreeSet, you can read my last article:

Detailed Set Collection

Here is a detailed introduction to this TreeSet, in fact, TreeMap is nothing special, let's take a look at the source code:

	public TreeMap(Comparator<? super K> var1) {
    
    
        this.comparator = var1;
    }

It can be seen from this that the TreeMap based on the sorting tree that implements a custom order is the same, just like the TreeSet!

5.2.1. Look at the only difference between TreeMap and TreeSet

The objects sorted by TreeSet are the elements in the TreeSet collection, and the objects sorted in the Tree Map are the keys of each key-value pair!

5.2.2. Look at an example of natural sorting:

package MapInterface;

import java.util.*;

public class MyTreeMap {
    
    
    public static void main(String[] args){
    
    
        TreeMap myTreeMap = new TreeMap();
        myTreeMap.put("stu4", 1);
        myTreeMap.put("stu5", 2);
        myTreeMap.put("stu3", 3);
        myTreeMap.put("stu2", 4);
        myTreeMap.put("stu1", 5);

        Iterator iterator = myTreeMap.entrySet().iterator();
        while (iterator.hasNext()){
    
    
            Map.Entry entry = (Map.Entry)iterator.next();
            Object k = entry.getKey();
            Object v = entry.getValue();
            System.out.println("key = " + k + " , value = " + v);
        }
    }
}

Then take a look at the output of this example:
Insert picture description here
it is clear that what we see is a collection of TreeMap sorted by key (dictionary order)

5.2.3. Look at an example of custom sorting:

package MapInterface;

import java.util.*;

public class MyTreeMap {
    
    
    public static void main(String[] args){
    
    
        TreeMap myTreeMap = new TreeMap(new MyComparetor());
        myTreeMap.put("stu4", 1);
        myTreeMap.put("stu5", 2);
        myTreeMap.put("stu3", 3);
        myTreeMap.put("stu2", 4);
        myTreeMap.put("stu1", 5);

        Iterator iterator = myTreeMap.entrySet().iterator();
        while (iterator.hasNext()){
    
    
            Map.Entry entry = (Map.Entry)iterator.next();
            Object k = entry.getKey();
            Object v = entry.getValue();
            System.out.println("key = " + k + " , value = " + v);
        }
    }
}

class MyComparetor implements Comparator{
    
    

    @Override
    public int compare(Object o1, Object o2) {
    
    
        String s1 = (String)o1;
        String s2 = (String)o2;
        return s2.compareTo(s1);
    }
}

Take another look at this custom sorting example, the output result is:

Insert picture description here
This is very simple, so I won't repeat the reasons. For details, please refer to my last article, there is a link in front!

Guess you like

Origin blog.csdn.net/qq_44274276/article/details/107800723