map in java key value - How to iterate HashMap in java using foreach loop

How to iterate HashMap in java using foreach loop

Posted on

map in java key value - How to iterate HashMap in java using foreach loop

The HashMap class makes use of a hash desk to implement the Map interface. This enables the execution time of fundamental operations, resembling get() and put(), to stay fixed even for big units. HashMap implements Map and extends AbstractMap. It doesn’t add any strategies of its personal.

As soon as ought to notice following options of HashMap as compair to different collections.

  • HashMap doesn’t assure the order of its components.The order through which components are added to a hash map just isn’t essentially the order through which they’re learn by an iterator.
  • HashMap just isn’t synchronized, this makes HashMap higher for non-threaded purposes, as unsynchronized Objects sometimes carry out higher than synchronized ones.An equivalently synchronised HashMap could be obtained by: Collections.synchronizedMap(myMap)
  • HashMap permits one null key and any variety of null values.
  • HashMap’s subclass LinkedHashMap with predictable iteration order (which is insertion order by default), this implementation differs from HashMap.

Let’s see how we Iterate HashMap utilizing for-each loop in java. I’m creating a category Tackle which is a member variable of Consumer class. Following code exhibits Tackle class.

and Consumer class…

Put Consumer objects in HashMap and iterate utilizing for-each loop. First we’re changing Map into Set utilizing entrySet() methodology, foreach loop go to every Entry out there and return Entry in each go to.

Supply techzoo.org