Java - View of the keys and values of a map

Subscribe Send me a message home page


The keySet() and values() methods of a Map have a very "strange" behavior. According to the documentation, they provide a view of keys and values of the map. When we modify this view, the underlying map instance will be modified as well. It seems that this design is here because it is more efficient.

The code below illustrates this "surprising" behavior:
public class Main {

    public static void main(String[] args) {

        Map<String, String> myMap = new HashMap<>();
        myMap.put("key1", "value1");
        myMap.put("key2", "value2");

        Set<String> keyView = myMap.keySet();

        System.out.println("size of the map before removing key1: " + myMap.size());
        keyView.remove("key1");
        System.out.println("size of the map after removing key1: " + myMap.size());

        Collection<String> valueView = myMap.values();
        System.out.println("size of the map before removing value2: " + myMap.size());
        valueView.remove("value2");
        System.out.println("size of the map after removing value2: " + myMap.size());

    }
}
And here is the output of the program:
size of the map before removing key1: 2
size of the map after removing key1: 1
size of the map before removing value2: 1
size of the map after removing value2: 0

----- END -----

Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png


Comments