Examples to Loop Map in Java - Foreach vs
Iterator
There are multiple ways to loop
through Map in Java, you can either use foreach loop or Iterator to traverse
Map in Java, but all ways use either Set of keys or values for iteration. Since
Map by default doesn't guarantee any order, any code which assumes a particular
order during iteration will fail. You only want to traverse or loop through a
Map, if you want to transform each mapping one by one. Now Java 8 release
provides a new way to loop through Map in Java using Stream API and forEach
method. For now, we will see 3 ways to loop through each elements of Map.
Though Map is an interface in Java, we often loop through common Map
implementation like HashMap, Hashtable, TreeMap and LinkedHashMap. By the
way, all the ways of traversing Map discussed in this article is pretty general
and valid for any Map implementation, including proprietary and third-party Map
classes. What I mean by looping through Map is getting mappings one at a time,
processing them and moving forward. Let's say, we have a Map of Workers, after
appraisal every worker has got 8% hike, now our task is to update this Map, so
each worker object reflect its new, increased salary. In order to do this task,
we need to iterate through Map, get the Employee object, which is stored as
value. Update Worker with new salary, and move on. Did you ask about saving it
back to Map? no need; When you retrieve values from Map using get() method,
they are not removed from Map, so one reference of same object is always there
in Map, until you remove it. That's why, you just need to update object, no
need to save it back. By the way, remember to override equals() and hashCode()
method for any object, which you are using as key or value in Map. Internal
code of HashMap uses both of these method to insert and retrieve objects
into Map, to learn more see How Map works in Java.
|
0 comments:
Post a Comment