Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do we use entrySet() method and use the returned set to iterate a map?

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?

like image 815
priya Avatar asked Mar 25 '11 05:03

priya


People also ask

What is the use of entrySet in 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.

What is the return type of 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.

What is the return type of entrySet () in HashMap?

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.


1 Answers

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));
like image 148
Peter Lawrey Avatar answered Nov 01 '22 18:11

Peter Lawrey