How to create iterators for hashmap in Java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to create iterators for hashmap in Java?

12th Mar 2021, 5:52 AM
Saurav Kokane
Saurav Kokane - avatar
3 Answers
+ 1
See if this helps your_HashMap.forEach((k,v) -> your statement);
12th Mar 2021, 9:33 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
You have many ways: For only keys.... use keySet() method For only values... use values() For pair.... use entrySet() All of these return a Collection where you have an iterator() method Read docs... https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Map.html Example JDK10+: for (var it = myMap.entrySet().iterator(); it.hasNext();) { var entry = it.next(); var key = entry.getKey(); var value = entry.getValue(); ..... } This is the imperative programming way. If you need mutate states I recommed you adopt functional programming using Stream and lambda functions to preserve data Inmutability The basic... myMap.forEach((key, value) -> { ...... }); Advanced.... through methods I tell you at the begining and using their .stream() as start point to beging chain operations. https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/stream/package-summary.html
13th Mar 2021, 12:36 AM
David Ordás
David Ordás - avatar