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

这里是Map.Entry的官方解释

public static interface Map.Entry

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 m : map.entrySet()) {  
              System.out.println("key:"+m.getKey()+" value"+m.getValue());  
          }   

Map.Entry
中提供了getKey()和getValue()方法,这两个方法的作用很明显一个获得key一个获得value相比以前遍历Map方便很多尤其是Map比较复杂的时候

你可能感兴趣的:(Java)