Home > Java > Javagetting Started > body text

What are the several ways of map traversal?

王林
Release: 2022-01-12 15:53:11
Original
77956 people have browsed it

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.

What are the several ways of map traversal?

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");
Copy after login

Method one, for loop

for(Map.Entry<String, String> entry:map.entrySet()){  
        System.out.println(entry.getKey()+"--->"+entry.getValue());  
    }
Copy after login

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());  
    }
Copy after login

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);  
    }
Copy after login

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());
     }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!