Map keySet, values should not be used

I got a warning that I can use ʻentrySet ()` in findbugs even with code that uses only key like ↓.

for(var key : map.keySet()){
    // map.get(key)Processing that uses only key purely without doing such things
}

I interpreted that ʻentrySet () is more efficient if both key and value ** are used, so if only one is used, isn't it related to efficiency? Rather, ʻEntry <K, V> has both key and value, so I think that one of the unnecessary resources is wasted, so I will look at the internal implementation for trade-in.

AbstractMap.java


public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new AbstractSet<K>() {
                public Iterator<K> iterator() {
                    return new Iterator<K>() {
                        private Iterator<Entry<K,V>> i = entrySet().iterator();
                        
                        //Abbreviation

                    };
                }
            };
            keySet = ks;
        }
        return ks;
    }

If there is no keySet, it is created and stored in the field, but it can be seen that ʻentrySet (). Iterator () is called to initialize ʻIterator <K>. After all, it seems that keySet () and values () go through ʻentrySet ()`.

In other words, the warning that you should use ʻentrySet ()` to stop thinking, even if you have only one of the key or value, was ** correct **.

Recommended Posts

Map keySet, values should not be used
[Java] When var should be used and when it should not be used
Three reasons why wrapper classes should not be used in Java
Gekitsuyo RestTemplate should be used for REST communication
[RubyOnRails] What kind of data should active_hash be used for?
The case that @Autowired could not be used in JUnit5