java Foundation: Map mapping

Map mapping

  • public interface Map<K,V>

  • An object that maps keys to values. A mapping cannot contain duplicate keys; Each key can be mapped to at most one value.

  • Type parameter:

    • K - the type of key maintained by this mapping
    • V - type of mapped value
  • Implementation classes: HashMap, Hashtable, LinkedHashMap

  • Summary:

    1. Map stores key value pairs and the mapping relationship between them
    2. The key of Map cannot be duplicate
    3. Each key in the Map can only correspond to one value

method

  1. V put(K key, V value): associate the specified value with the specified key in this map (optional operation).

    1. If the current key already exists in the map, calling the put method to add will overwrite the previous Value value;

    2. If there is no currently added key in the map, the return value is null; If the current key already exists in the map, the return value is the overwritten value;

  2. void clear(): removes all mapping relationships from this mapping (optional).

  3. boolean containsKey(Object key): returns true if the mapping contains the mapping relationship of the specified key.

  4. boolean containsValue(Object value): returns true if this mapping maps one or more keys to the specified value.

  5. V get(Object key): returns the value mapped by the specified key; Returns null if the mapping does not contain a mapping relationship for the key

  6. boolean isEmpty(): returns true if the mapping does not contain a key value mapping relationship.

  7. Set < k > keyset(): returns the set view of the keys contained in this map

    The reason why the return value is a Set set is that the key of the Map is unique

  8. Collection < V > values(): returns the collection view of the values contained in this map

  9. V remove(Object key): if there is a key mapping relationship, remove it from this mapping (optional operation).

  10. int size(): returns the number of key value mapping relationships in this mapping.

  11. Set < map. Entry < K, V > > entryset(): returns the set view of the mapping relationship contained in this mapping.

public class MapDemo2 {
    public static void main(String[] args) {
        // Object to create Map
        Map<String,Integer> map = new HashMap<String,Integer>();
        // put() add element
        System.out.println(map.put("001",28));  // null
        System.out.println(map.put("002",17));  // null
        System.out.println(map.put("001",60));  //28
        // No error is reported during compilation. If it is repeated, value will be overwritten

        // Override toString() Key = Value
        System.out.println(map);  // {001=60, 002=17}

        // containsKey()
        System.out.println(map.containsKey("002"));  // true
        // containsValue()
        System.out.println(map.containsValue(28));  // false

        // equals()
        Map<String, Integer> copyMap = new HashMap<String,Integer>();
        copyMap.putAll(map);
        System.out.println(map.equals(copyMap));  // true

        // get(key)
        int num = map.get("001");  // Automatic unpacking
        // int num1 = map.get("008");  // error
        // map.get("008");  Return null
        // Null. Intvalue() called during automatic unpacking -- > null pointer exception
        System.out.println(map.get("008"));  // null

        // Set < k > keyset(): put the key value into a set
        Set<String> keys = map.keySet();
        // Values(): returns the set formed by values
        Collection<Integer> col = map.values();
        System.out.println(keys+"\n"+col);

        // remove(key)
        int tmp = copyMap.remove("001");
        System.out.println(tmp);

        // size()
        System.out.println(map.size());
    }
}

How to traverse Map

  • Scheme I:
    1. KeySet get the Set of all key s
    2. Traverse Set set
    3. Get the corresponding value according to the value of the key
  • Scheme II:
    1. Call entrySet() to get the Set of Entry objects representing Map key value pairs
    2. Traverse Set set
    3. Call the method of Entry to obtain the key and value respectively
      • K getKey(): returns the key corresponding to this item.
      • V getValue(): returns the value corresponding to this item.
// ergodic
// Scheme I:
// 1. keySet get the set of all key s
Set<String> keys = map.keySet();
// 2. Traverse the set
for (String str: keys){
    // 3. Obtain the corresponding value according to the value of the key
    System.out.println(str+"="+map.get(str));
}
// Scheme II:
// 1. Call entrySet() to get the Set of Entry objects representing Map key value pairs
Set<Map.Entry<String,Integer>> entries = map.entrySet();
// 2. Traverse Set
for (Map.Entry<String,Integer> entry : entries){
    // 3. Call the Entry method to obtain the key and value respectively
    System.out.println(entry.getKey() + "=" + entry.getValue());
}
// Simplified version
for(Map.Entry<String,Integer> entry: map.entrySet()){
    System.out.println(entry.getKey() + "=" + entry.getValue());
}

HashMap

  • Implementation based on array linked list

  • In order to improve the efficiency, the bottom layer of HashMap will be optimized accordingly

  • JDK1.8, when the chain length of the linked list exceeds 8, it will turn into a red black tree; After deleting the element, when the length of the linked list is less than 6, it returns to the linked list

  • The key of HashMap can be null, but there is only one; The value of HashMap can be null without limiting the number

  • Asynchronous threads are unsafe

  • Construction method:

  • HashMap(): construct an empty HashMap with default initial capacity (16) and default load (load, load) factor (0.75); When it exceeds 16 * 0.75 = 12, start capacity expansion and double the capacity each time

  • Method: no special method

Hashtable

  • Start with the following version: JDK1.0
  • Feature: key values cannot be null
  • Synchronous thread safety
  • Construction method
    • Hashtable(): construct a new empty hash table with the default initial capacity (11) and load factor (0.75).
public class HashtableDemo {
    public static void main(String[] args) {
        // Create object Hashtable
        Hashtable<String,Integer> table = new Hashtable<String, Integer>();
        //
        table.put("start",12);  // Automatic packing
        table.put("hello",15);
        table.put("java",30);

        System.out.println(table);

        // ergodic
        // 1. The iterator elements can only output value
        Enumeration<Integer> ele = table.elements();
        Enumeration<String> keys = table.keys();
        while(keys.hasMoreElements()){
            System.out.println(keys.nextElement() + "=" + ele.nextElement());
        }
        // 2. entrySet()
        Set<Map.Entry<String,Integer>> entries = table.entrySet();
        for(Map.Entry<String,Integer> entry: entries){
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
        // Simplified version
        for(Map.Entry<String,Integer> entry: table.entrySet()){
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    }
}

Differences between HashMap and Hashtable:

  1. HashMap JDK1.2ï¼›Hashtable JDK1.0

  2. The initial capacity of HashMap is 16 and the loading factor is 0.75; Capacity expansion: double the capacity each time;

    The initial capacity of Hashtable is 11 and the loading factor is 0.75; Double + 1 for each expansion;

  3. HashMap asynchronous thread is unsafe and efficient

    HashTable synchronous thread safety, low efficiency

  4. HashMap key value can be null, and only one key can be null

    No Hashtable key value can be null

Note: both HashMap and Hashtable are out of order. LinkedHashMap can ensure the order of storage

Keywords: Java Back-end

Added by tores on Wed, 08 Dec 2021 12:33:12 +0200