开发者

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()){
    M开发者_运维问答ap.Entry m= (map.Entry) s.next();
    System.out.println(""+m.getKey()+""+ m.getValue());
}

Why do we iterate using a set why not directly map?


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));


Because, logically, a map is a Set collection of key-value pairs - which is what a Map.Entry represents. Iteration is an operation on a collection generally, not a map specifically.

However, I've often wondered myself why Map doesn't implement Iterable<Map.Entry<K,V>> et al and provide an iterator() method over the map entries directly instead of requiring an entry set (which it could certainly do also to provide a full Set API.


Map is a collection of pairs of things, right (Entries). So you can iterate over entries, or iterate over the keys only (map.keySet()), or over the value only (map.values()). What else do you want to be able to iterate over?


Because Java doesn't have a better syntax to do it. (Yours can be improved)

It would be nice to

for(String key, Integer val : map)
    print(key, val);

or

map.foreach (String key, Integer val) -> print(key, val);

but Java doesn't have these.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜