keySet() vs entrySet vs values() Example in Java Map

The java.util.Map interface provides three methods keySet(), entrySet() and values() to retrieve all keys, entries (a key-value pair), and values. Since these methods directly come from the Map interface, you can use it with any of the Map implementation class e.g. HashMap, TreeMap, LinkedHashMap, Hashtable, ConcurrentHashMap, and even with specialized Map implementations like EnumMap, WeakHashMapand IdentityHashMap. In order to become a good Java developer, it's important to understand and remember key classes Java API e.g. Java's Collection framework. In this article, we will not only learn the difference between keySet(), entrySet() and values() methods, but also learn how to use them in Java program by looking at a simple example.


The keySet() method

This method returns a Set view of all the keys in the map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the Set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined.

The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove(), Set.remove(), removeAll(), retainAll(), and clear() operations, but It does not support the add() or addAll() operations.


You can also use the keySet() method to iterate over a Java HashMap as shown in the following example:

// Iterating using keySet() method of HashMap
Set<String> keys = priceMap.keySet();        
for(String key: keys){
   Integer value = priceMap.get(key);
   System.out.printf("key: %s, value: %d %n", key, value);
}

Output:
key: Car, value: 20000 
key: Phone, value: 200 
key: Bike, value: 6000 
key: Furniture, value: 700 
key: TV, value: 500 


The entrySet() method

The entrySet() method of Map interface returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue() operation on a map entry returned by the iterator) the results of the iteration are undefined.

The Set also supports element removals, which removes the corresponding mapping from the map, via the Iterator.remove(), Set.remove(), removeAll(), retainAll(), and clear() operations. It does not support the add() or addAll() operations.

You can also read Core Java for the Impatient by Cay S. Horstmann to learn about different views of Collection in Java. One of the best books to learn Java programming at the moment. It also covers Java SE 8.

keySet() vs entrySet() vs values() example in Java HashMap



Here is an example of how you can traverse over a Map in Java using the entrySet() method. This is by far the most efficient way of iterating over Map out of several ways we have discussed earlier.

// traversing Map using entrySet() method
Set<Entry<String, Integer>> entries = priceMap.entrySet();
        
for(Map.Entry<String, Integer> entry : entries){
   String key = entry.getKey();
   Integer value = entry.getValue();
   System.out.printf("key: %s, value: %d %n", key, value);
}


The values() methods

The values() methods of Map interface returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove(), Collection.remove(), removeAll(), retainAll() and clear() operations.

Similar to keySet() and entrySet(), It does not support the add() or addAll() operations.

Here is how you can get all the values from a Map in Java:

Collection<Integer> values = priceMap.values();

Here is nice slid of summarizing different views of Map interface in Java:

keySet() vs entrySet vs values() Example in Java


How to use keySet(), entrySet(), and values() in Java

Here is our sample Java program to show you how you can use the keySet(), entrySet() and values() in you Java Program. I have just shown how you retrieve the respective view. I leave it to you what you want to do with those sets. For example, you can iterate over the Set to print the mapping, or remove any specific mapping depending upon some business logic.


Java Program to use keySet(), entrySet() and values()

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Java Program to demonstrate how to use keySet(), values() and entrySet()
 * method of HashMap.
 *
 * @author WINDOWS 8
 *
 */
public class HashMapDemo {

    public static void main(String[] args) {

        Map<String, Integer> priceMap = new HashMap<>();

        priceMap.put("TV", 500);
        priceMap.put("Phone", 200);
        priceMap.put("Car", 20000);
        priceMap.put("Bike", 6000);
        priceMap.put("Furniture", 700);

        System.out.println("price map: " + priceMap);

        Set<String> keys = priceMap.keySet();
        Collection<Integer> values = priceMap.values();
        Set<Entry<String, Integer>> entries = priceMap.entrySet();

        System.out.println("keys of Map : " + keys);
        System.out.println("values from Map :" + values);
        System.out.println("entries from Map :" + entries);

    }

}

Output:
price map: {Car=20000, Phone=200, Bike=6000, Furniture=700, TV=500}
keys of Map : [Car, Phone, Bike, Furniture, TV]
values from Map :[20000, 200, 6000, 700, 500]
entries from Map :[Car=20000, Phone=200, Bike=6000, Furniture=700, TV=500]


That's all about keySet() vs entrySet() vs values() method in Java. You have learned how you can obtain a different view from your Map in Java. This technique is applicable to all Map implementation including HashMap and ConcurrentHashMap. You can use these methods to iterate over Map as well as for removing entries from Map in Java.

Btw, you should be mindful that these methods return collections that can be modified automatically when the underlying collection changes. This can create thread-safety issues in concurrent Java programs. You can further read Core Java Volume 1 - Fundamentals by Cay S. Horstmann to learn about this sophisticated technique of providing view instead of creating separate Map classes. 

1 comment:

  1. in above example use Map.Entry other wise it give error remove argument

    ReplyDelete