Usually we write this to get the keys and values from a map.
Map m=new HashMap();
Set s=map.entrySet();
Iterator i=s.iterator()
while(s.hasNext()){
Map.Entry m= (map.Entry) s.next();
System.out.println(""+m.getKey()+""+ m.getValue());
}
Why do we iterate using a set why not directly map?
entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map or we can create a new set and store the map elements into them. Parameters: The method does not take any parameter.
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.
The Java HashMap entrySet() returns a set view of all the mappings (entries) present in the hashmap. Here, hashmap is an object of the HashMap class.
This is as close to iterating over the map as we can because you have to say whether you want just the keys, just the values or the whole key/value entry. For Sets and Lists, there is only one option so, no need to have a separate method to do this.
BTW: This is how I would iterate over a Map. Note the use of generics, the for-each loop and the LinkedHashMap so the entries appear in some kind of logical order. TreeMap would be another good choice.
Map<K,V> m=new LinkedHashMap<K,V>();
for(Map.Entry<K,V> entry: m.entrySet())
System.out.println(entry.getKey() + ": " + entry.getValue());
In Java 8 you can write
m.forEach((k, v) -> System.out.println(k + ": " + v));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With