Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me why we use set to iterate and why we don't go for map?

Map m=new HashMap();

Set s=map.entrySet();

Iterator i=s.iterator()

while(s.hasNext()){

    Map.Entry m= (map.Entry) s.next();

    System.out.println(""+m.getKey()+""+ m.getValue());

}

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

Basically, using sets and lists we can iterate for the key or values or the whole key/value entity. Also, you can use the below code as well:

Map<K,V> m=new LinkedHashMap<K,V>();

for(Map.Entry<K,V> entry: m.entrySet())

    System.out.println(entry.getKey() + ": " + entry.getValue());

I hope this will help.

Want to know more about Java? Prefer this tutorial on Learn Java.

Want to become a Java Expert? Join Java Certification now!!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 20, 2019 in Java by Anvi (10.2k points)

Browse Categories

...