您的位置:首页 > 编程语言 > Java开发

Map.Entry和map.entrySet()---更好的遍历Map

2017-07-30 10:31 288 查看
这里是Map.Entry的官方解释

public static interface Map.Entry<K,V>

A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.


上面的意思就是Map.Entry()返回的是当前Map的item,但是这个方法只在遍历的时候有用,上面也提到了map.entrySet()方法,返回的是当前Map的item Set集合。

Map.entrySet() 这个方法返回的是一个Set

for (Map.Entry<String, String> m : map.entrySet()) {
System.out.println("key:"+m.getKey()+" value"+m.getValue());
}


Map.Entry

中提供了getKey()和getValue()方法,这两个方法的作用很明显一个获得key一个获得value相比以前遍历Map方便很多尤其是Map比较复杂的时候
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java map 遍历