Four traversals of map

//Four traversal methods of map

//Map cannot be traversed directly, but only indirectly by traversing key and value

public static void main(String[] args) {

Map
map = new HashMap

(); map. put("1","value1"); map. put("2","value2"); map. put("3","value3"); // The first one is widely used, and the secondary value is system out. Println ("traverse key and value:") through map.keyset); for (String key : map.keySet()) { System.out.println("key= "+ key + " and value= " + map.get(key)); } // The second system out. Println ("use iterator to traverse key and value:") through map.entryset); Iterator
> it = map. entrySet(). iterator(); while (it.hasNext()) { Map.Entry

entry = it.next(); System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); } // The third type: recommended, especially when the capacity is large out. Println ("traverse key and value through map.entryset"); for (Map.Entry

entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }



//The fourth system out. Println ("traverse all values through map. Values(), but not keys"); for (String v : map.values()) { System.out.println("value= " + v); } }

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>