2021-11-07 HashMap operation, summarize

Check every HashMap operation, and finally take the time to summarize it

1, Basic operation of HashMap
1. Create

HashMap<Integer,String> map = new HashMap<>();

2. Add

//Time complexity O(1), obtain the memory address through the hash function, and then put it into memory
//map.put(key,value)
map.put(1,"lihua");

3. Renew

map.put(1,"huahua");

4. Delete element

//Time complexity 	 O (1), find the element directly, and then operate
map.remove(1)

5. Get element

//Time complexity O (1)
//The key can be obtained directly through the hash function
//map.get(key)
map.get(1);
//The value is the corresponding value

6. Check whether the key exists

//Return true or false
map.containsKey(1);

2, HashMap get < key, value >
1. Iterator

(a)

//A little more efficient
  HashMap<String,String> map = new HashMap<>();
  Iterator iter = map.entrySet().iterator();
  while (iter.hasNext()) {
  Map.Entry entry = (Map.Entry) iter.next();
  Object key = entry.getKey();
  Object val = entry.getValue();


  }

(b)

 Map map = new HashMap();
  Iterator iter = map.keySet().iterator();
  while (iter.hasNext()) {
  Object key = iter.next();
  Object val = map.get(key);
  }
 

2,foreach
(a)

HashMap<String,String> map = new HashMap<>();
Set<Entry<String, Integer>> en = map.entrySet();
		for(Entry<String, Integer> entry : en) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}

(b)

Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
	map.get(key);
}

The map.entrySet() here needs to dig deep
The entrySet() method of the HashMap method returns a Set object. Many people think that the returned object is a Set object that contains all the key value pairs in the Map. This understanding is not accurate. How to say, through this Set object, we can really get all the key value pairs stored in the Map, However, the collection object itself does not store data. It just helps us traverse the data in the Map, similar to Iterator. In fact, the key of HashMap is not added to the EntrySet collection. Instead, the Iterator is used to traverse the key during traversal. This is the conclusion. Let's take a look at the reason and process.

entrySet() source code:

public Set<Entry<K, V>> entrySet() {
        Set var1;
        return (var1 = this.entrySet) == null ? (this.entrySet = new HashMap.EntrySet()) : var1;
    }

A reference entryset maintained internally by HashMap. This application is of type entryset. But let's find out when the entryset is filled with data in the source code of HashMap, and then look at the class definition of entryset:

final class EntrySet extends AbstractSet<Entry<K, V>> {
        EntrySet() {
        }

        public final int size() {
            return HashMap.this.size;
        }

        public final void clear() {
            HashMap.this.clear();
        }

        public final Iterator<Entry<K, V>> iterator() {
            return HashMap.this.new EntryIterator();
        }

        public final boolean contains(Object var1) {
            if (!(var1 instanceof Entry)) {
                return false;
            } else {
                Entry var2 = (Entry)var1;
                Object var3 = var2.getKey();
                HashMap.Node var4 = HashMap.this.getNode(HashMap.hash(var3), var3);
                return var4 != null && var4.equals(var2);
            }
        }

        public final boolean remove(Object var1) {
            if (var1 instanceof Entry) {
                Entry var2 = (Entry)var1;
                Object var3 = var2.getKey();
                Object var4 = var2.getValue();
                return HashMap.this.removeNode(HashMap.hash(var3), var3, var4, true, true) != null;
            } else {
                return false;
            }
        }

        public final Spliterator<Entry<K, V>> spliterator() {
            return new HashMap.EntrySpliterator(HashMap.this, 0, -1, 0, 0);
        }

        public final void forEach(Consumer<? super Entry<K, V>> var1) {
            if (var1 == null) {
                throw new NullPointerException();
            } else {
                HashMap.Node[] var2;
                if (HashMap.this.size > 0 && (var2 = HashMap.this.table) != null) {
                    int var3 = HashMap.this.modCount;

                    for(int var4 = 0; var4 < var2.length; ++var4) {
                        for(HashMap.Node var5 = var2[var4]; var5 != null; var5 = var5.next) {
                            var1.accept(var5);
                        }
                    }

                    if (HashMap.this.modCount != var3) {
                        throw new ConcurrentModificationException();
                    }
                }

            }
        }
    }

The iterator function in the EntrySet class returns an object of the iterator < entry < K, V > > class, that is, HashMap. This. New entryitator(). This iterator actually operates on the caller object. In other words, when using the iterator to traverse the elements in the set, the iterator of the EntrySet class will ensure that the set of key value pairs of the nodes of the HashMap can be obtained in turn. This is the essence of our process of traversing the EntrySet.
HashMap.entrySet() itself is not difficult. This method does not return a collection of stored data, it is just a view window.

The method of keySet() is similar. You can see this blog The keySet() method of source code parsing HashMap

3, Get key through value

Method 1:
1,
Get a corresponding key according to the value

     public  String getKey(HashMap<String,String> map,String value){
        String key = null;
         //Map and HashMap do not implement Iteratable interface. They cannot be used to enhance for loop
         for(String getKey: map.keySet()){
             if(map.get(getKey).equals(value)){
                 key = getKey;
             }
        }
         return key;
        //This key must be the last key that satisfies this condition
     }

2. Get all the corresponding key values according to the value value

     public  List<String> getKeyList(HashMap<String,String> map,String value){
         List<String> keyList = new ArrayList();
        for(String getKey: map.keySet()){
             if(map.get(getKey).equals(value)){
                 keyList.add(getKey);
             }
         }
         return keyList;
    }

Method 2:

public ArrayList<String> getKey(String value) {
         ArrayList<String> keyList = new ArrayList<String>();
         String key = null;
         Set<Entry<String, String>> set = map.entrySet();
        
        Iterator it = set.iterator();
         while (it.hasNext()) {
             Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();

             if (entry.getValue().equals(value)){
                 key = (String) entry.getKey();
                 keyList.add(key);
             }
         }

Keywords: Java Back-end HashMap

Added by trent2800 on Mon, 08 Nov 2021 00:01:38 +0200