Monday 12 March 2012

keySet(), entrySet() and values() in Java Map

java.util.Map<K,V> interface provides three methods keySet(), values() and entrySet() for retrieving keys, values and key-value pairs respectively.Let us discuss about it one by one.

public Set<K> keySet()

Returns a Set view of the keys 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), 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. It does not support the add or addAll operations.

public Collection<V> values()

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. It does not support theadd or addAll operations.


public Set<Map.Entry<K,V>> entrySet()

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 supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clearoperations. It does not support the add or addAll operations.

See the example given below

import java.util.*;
import java.util.Map.Entry;

public class Main {

public static void main(String args[]) {

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 10);
map.put(2, 20);
map.put(3, 30);
map.put(4, 40);
map.put(5, 50);
Set<Integer> keySet = map.keySet();
System.out.println("Key Set is:" + keySet);
Collection<Integer> values = map.values();
System.out.println("Values are:" + values);
System.out.println("Key-Value pairs are:");
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
for (Entry<Integer, Integer> entry : entrySet) {
System.out.println("key=" + entry.getKey() + " value="
+ entry.getValue());
}

}
}

The output is

Key Set is:[1, 2, 3, 4, 5]
Values are:[10, 20, 30, 40, 50]
Key-Value pairs are:
key=1 value=10
key=2 value=20
key=3 value=30
key=4 value=40
key=5 value=50

No comments:

Post a Comment