Preview for the new semester? Method and example explanation of data structure collection framework Map

Posted by rgilchrist on Sat, 18 Dec 2021 15:31:13 +0100

1, Map interface

Map properties:
The most prominent feature of the Map interface is that there is a relationship between keys and values. You can obtain values through keys.

1.1 concept and application scenario

Map is a container or data structure specially used for search, and its search efficiency is related to its specific instantiation subclasses. Previous common search methods include:

  1. Direct traversal. The time complexity is O(N). If there are many elements, the efficiency will be very slow
  2. The time complexity of binary search is, but the sequence must be ordered before search.

The above sorting is more suitable for static type search, that is, the interval is generally not inserted or deleted, but in reality, such as:

  1. Query test scores by name
  2. Address book, that is, to query the contact information according to the name
  3. Do not duplicate the collection, that is, you need to search whether the keyword is already in the collection
    Some insertion and deletion operations, i.e. dynamic search, may be performed during search, so the above two methods are not suitable. The Map described in this section is a collection container suitable for dynamic search.

1.2. Two models of Map

Generally, the searched data is called keyword key, the Value corresponding to the keyword is called Value, and a pair of key values is called key Value pair. There are two such models:

1: Pure key model, such as:
There is an English dictionary to quickly find out whether a word is in the dictionary. Quickly find out if a name is in the address book

2. Key value model, for example:
Count the number of occurrences of each word in the file. The statistical resu lt is that each word has its corresponding number: < word, number of occurrences of word >
Liangshan hero's Jianghu nickname: every hero has his own Jianghu nickname
The key value pairs stored in the Map are key value pairs.

1.3 inheritance relationship between Map interface and other collection frameworks


Through the above figure, we find that the Map interface is relatively independent from list, set and queue. It has three subclasses, HashMap, TreeMap and SortMap.

1.4 description of Map interface

Map is an interface class, which does not inherit from Collection. The key value pairs of < K, V > structure are stored in this class, and K must be unique and cannot be repeated.
Knock on the blackboard!!!, The K of Map must be unique. Just like the corresponding law of function, it can be one to many, but not many to one. Using this feature, Map can be very helpful when you encounter the problem of counting times in the future.

2, Common methods of Map

2.1 put(K key,V value) put the specified KV pair into the map

//First create a map instance
Map<Integer,String> map=new HashMap<>();
   map.put(601,"birthday");
   map.put(2001,"Year of birth");
   System.out.println(map);

Key and value are separated by. The specific types are the same as those when creating an instance above.

2.2,getOrDefault(Object K,V defaultValue)

Return the value corresponding to the key. If the key does not exist, return the default value. The default value is defined by yourself.

 // What can be found
System.out.println("What can be found + Corresponding Value value"+map.getOrDefault(2001,"I can find it"));
 //Case not found
System.out.println("Case not found + Corresponding Value value"+map.getOrDefault(258,"Didn't find 111 instead"));

The effects are as follows:

In the first article, we put two pairs of data: birthday and year of birth. Here we use the getOrDefault method to test.

2.3,boolean containsValue(Object K)

Judge whether value exists, and the return value is Boolean.

  //What can be found
System.out.println("Can you find your birthday   "+map.containsValue("birthday"));
//A situation that cannot be found
System.out.println("Can you find the year of birth    "+map.containsValue("Year of birth"));

The effects are as follows:

2.4,boolean containsKey(Object K)

 //What can be found
 System.out.println("Can you find 601  "+map.containsKey(601));
//Case not found
 System.out.println("Can you find 602  "+map.containsKey(602));

The effect is similar to the above, except that the above value is replaced by a key.

2.5,set<Map.Entry<K,V>> entrySet()

To return all Key value mapping relationships is to return a pair of keys and their corresponding vaules as a whole, and this set contains all relationship pairs of the current map. It is generally used to traverse a map.

 /*4:set<Map.Entry<K,V>> entrySet()
        Returns all key value pairs
        Is to return an entire key and value as a value.            
        for each Usage: on the left is the variable type and variable name (variable name can be arbitrary), and on the right is the object to be traversed
         */
        System.out.println("Map.enteySet");
        for (Map.Entry<Integer,String> entry :map.entrySet()) {
            System.out.print(entry.getKey()+"     ");
            System.out.print(entry.getValue()+"     ");
        }
        System.out.println();

The effects are as follows:

Here I use the method for each and use entry in the loop GetKey and entry GetValue method, so that each key and value in the map are printed separately.

2.6 about map Description of entry < K, V >

Map. Entry < K, V > is an internal class implemented in map to store the mapping relationship between < Key, value > Key value pairs. This internal class mainly provides the acquisition of < Key, value >, the setting of value and the comparison method of keys.

It includes the following methods:

2.7,boolean isEmpty()

Judge whether the current map is empty

 System.out.println("Now is a non empty return"+map.isEmpty());

The current map is not empty, so false is returned.

2.8,int size()

The number of returned key value pairs is the number of groups of data

  System.out.println("current map Number of key value pairs   "+map.size());

3, Method example

Let's create an example to practice. TreeMap is used here to instantiate the Map. You can try HashMap exercise.

Map<String, String> m = new TreeMap<>();
// put(key, value): insert the key value pair of key value
// If the key does not exist, the key value pair of key value will be inserted into the map and null will be returned
m.put("Lin Chong", "Leopard head");
m.put("lu zhishen", "monk who doesn't follow the rituals");
m.put("Wu Song", "Walker");
m.put("Song Jiang", "Timely rain");
String str = m.put("Li Kui", "Black Whirlwind");
System.out.println(m.size());
System.out.println(m);
// put(key,value): note that key cannot be empty, but value can be empty
// If the key is null, a null pointer exception will be thrown
//m.put(null, "flower name");
str = m.put("unknown", null);
System.out.println(m.size());
// put(key, value):
// If the key exists, it will replace the value corresponding to the original key with value and return the old value
str = m.put("Li Kui", "Iron bull");
// get(key): returns the value corresponding to the key
// If the key exists, the value corresponding to the key is returned
// If the key does not exist, null is returned
System.out.println(m.get("lu zhishen"));
System.out.println(m.get("Shi Jin"));
//GetOrDefault(): returns the value corresponding to the key if the key exists; returns a default value if the key does not exist
System.out.println(m.getOrDefault("Li Kui", "Iron bull"));
System.out.println(m.getOrDefault("Shi Jin", "Nine striped Dragon"));
System.out.println(m.size());
//containKey(key): check whether the key is included in the Map. Time complexity: O(logN)
// Search according to the nature of red black tree
// true is returned when found, otherwise false is returned
System.out.println(m.containsKey("Lin Chong"));
System.out.println(m.containsKey("Shi Jin"));
// containValue(value): check whether value is included in the Map. Time complexity: O(N)
// Because TreeMap is organized by Key, it needs to traverse as a whole when finding value
// true is returned when found, otherwise false is returned
System.out.println(m.containsValue("Leopard head"));
System.out.println(m.containsValue("Nine striped Dragon"));

The operation effect is as follows:

4, End

Finally, I wish you all a smooth start to school. My article can help you preview in advance. You are no longer afraid of being unable to understand in class.

Topics: Java data structure