Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Java Map – keySet() vs. entrySet() vs. values() Methods

$
0
0

1. Overview

In this tutorial, we'll discuss the three methods keySet(), entrySet() and values() of the Map interface in Java. These methods are used to retrieve a set of keys, a set of key-value mappings, and collection of values, respectively.

2. Map Initialization

While we can use these methods on any class implementing the Map interface like HashMap, TreeMap, and LinkedHashMap, we'll work with HashMap here.

Let's create and initialize a HashMap whose key is of type String and value is of type Integer:

Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);

3. The keySet() Method

The keySet() method returns the Set of keys contained in the Map

Let's apply the method keySet() to the Map and store it in a Set variable actualValues:

Set<String> actualValues = map.keySet();

Now, let's confirm that the size of the returned Set is 2:

assertEquals(2, actualValues.size());

Further, we can see that the returned Set contains the keys of the Map:

assertTrue(actualValues.contains("one"));
assertTrue(actualValues.contains("two"));

4. The entrySet() Method

The entrySet() method returns the set of key-value mappings. The method doesn't take any parameters and has a return type Set of Map.Entry. 

Let's apply the method entrySet() to the Map:

Set<Map.Entry<String, Integer>> actualValues = map.entrySet();

As we can see, actualValues is a Set of Map.Entry objects.

Map.Entry is a static interface that holds both the key and the value. Internally, it has two implementations – AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry.

As before, let's confirm that the size of the returned Set is 2:

assertEquals(2, actualValues.size());

Furthermore, we can see that the returned Set contains the key-value entries of the Map:

assertTrue(actualValues.contains(new SimpleEntry<>("one", 1)));
assertTrue(actualValues.contains(new SimpleEntry<>("two", 2)));

Here, we've chosen the AbstractMap.SimpleEntry implementation of the interface Map.Entry for our test.

5. The values() Method

The values() method returns the Collection of values contained in the Map. The method doesn't take any parameters and has a return type Collection. 

Let's apply the method values() to the Map and store it in a Collection variable actualValues:

Collection<Integer> actualValues = map.values();

Now, let's verify the size of the returned Collection:

assertEquals(2, actualValues.size());

Further, we can see that the returned Set contains the values of the Map:

assertTrue(actualValues.contains(1));
assertTrue(actualValues.contains(2));

6. Conclusion

In this article, we've discussed the keySet()entrySet(), and values() methods of the Map interface.

As usual, the complete source code is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 4536

Trending Articles