The entrySet() method is used to get a Set view of the mappings contained in this map.
The keySet() method is used to get a Set view of the keys contained in this map.
Suppose we put a string array elements is a map where elements of string array is key and frequency of word is value, e.g.:
String[] args = {"if","it","is","to","be","it","is","up","me","to","delegate"};
then the map will have entries like
[ if:1 , it:2 .... ]
Set<String> keys = m.keySet();
System.out.println("keyset of the map : "+keys);
prints all keys:
"if","it","is","to","be","it","is","up","me","to","delegate"
Set<Map.Entry<String, Integer>> entrySet = m.entrySet();
Iterator<Map.Entry<String, Integer>> i = entrySet.iterator();
while(i.hasNext()){
Map.Entry<String, Integer> element = i.next();
System.out.println("Key: "+element.getKey()+" ,value: "+element.getValue());
}
prints all key values pairs :
Using entry set prints all values:
Key: if ,value: 1
Key: it ,value: 2
Key: is ,value: 2
Key: to ,value: 2
Key: be ,value: 1
Key: up ,value: 1
Key: me ,value: 1
Key: delegate ,value: 1
0 comments:
Post a Comment