Home >Java >Javagetting Started >What are the several ways of map traversal?
There are 4 ways to traverse map, namely: 1. Use for loop to traverse map; 2. Use iteration to traverse map; 3. Use keySet to iterate over map; 4. Use entrySet to traverse map.
Several ways to traverse the map are as follows:
(Learning video sharing: java teaching video)
java code:
Map<String,String> map=new HashMap<String,String>(); map.put("username", "qq"); map.put("passWord", "123"); map.put("userID", "1"); map.put("email", "qq@qq.com");
Method one, for loop
for(Map.Entry<String, String> entry:map.entrySet()){ System.out.println(entry.getKey()+"--->"+entry.getValue()); }
Method two, iteration
Set set = map.entrySet(); Iterator i = set.iterator(); while(i.hasNext()){ Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next(); System.out.println(entry1.getKey()+"=="+entry1.getValue()); }
Method three, keySet() iteration
Iterator it=map.keySet().iterator(); while(it.hasNext()){ String key; String value; key=it.next().toString(); value=map.get(key); System.out.println(key+"--"+value); }
Method 4, entrySet() iteration
Iterator it=map.entrySet().iterator(); System.out.println( map.entrySet().size()); String key; String value; while(it.hasNext()){ Map.Entry entry = (Map.Entry)it.next(); key=entry.getKey().toString(); value=entry.getValue().toString(); System.out.println(key+"===="+value); } for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }
Related recommendations: java introductory tutorial
The above is the detailed content of What are the several ways of map traversal?. For more information, please follow other related articles on the PHP Chinese website!