Two ways of Map traversal: keySet(), entrySet()

Example first

Map<String, Object> map = new HashMap<String, Object>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        map.put("key4", "value4");
        
        Set<String> set = map.keySet();
        Iterator<String> iterator = set.iterator();
        while(iterator.hasNext()) {
            String key = iterator.next();
            System.out.println(key);
            System.out.println(map.get(key));
        }
        
        Set<Entry<String, Object>> set1 = map.entrySet();
        for(Entry<String, Object> entry :set1) {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }

The main difference between the two is that keySet() can only get the key, and map.get(key) is needed when you need to get the value, and the source code is finally converted to Entry to get the value of the key.

So entrySet omits the separate operation of getting value.

keySet() will generate a KeyIterator iterator, and its next method only returns its key value:

private class KeyIterator extends HashIterator<K> {   
       public K next() {   
           return nextEntry().getKey();   
       }   
   }

entrySet() will generate an EntryIterator iterator, whose next method returns an instance of an Entry object, which contains key and value:

private class EntryIterator extends HashIterator<Map.Entry<K,V>> {   
       public Map.Entry<K,V> next() {   
           return nextEntry();   
       }   
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325331884&siteId=291194637