I have a structure in HashMap and I need to iterate through a for
. How can I do this iteration?
My code:
import java.util.HashMap;
import java.util.Map;
public class Testeo {
public static void main(String[] args) {
Map<Integer, String> datos = new HashMap<>();
datos.put(1, "uno");
datos.put(2, "dos");
datos.put(3, "tres");
//necesito iterar aquí
}
}
If you're using Java 8 you can take advantage of lambda expressions to write compact code:
There is no need to use
EntrySet
, the data types ofk
andv
are automatically inferred.There is no way to iterate over the HashMap directly, but you can iterate over it.
entrySet()
For example:
Source: Stack Overflow by Jesper
Reference link: How to Iterate Over a Map in Java
There are several ways to iterate over a map in java. We will see the most common methods and review their advantages and disadvantages. Since all maps in java implement the interface
Map
, the following techniques will work for any implementation ofMap
(HashMap
,TreeMap
,LinkedHashMap
,Hashtable
, etc.)Method #1: Iterating over the inputs using For-Each.
It is the most common and the most preferable in most cases. It would be used in the case that you need both value and key.
Note that the For-Each loop was introduced in Java 5 so it only works in early versions of java. Also the loop
For-Each
will throwNullPointerException
if you try to iterate over a mapnulo
, so always check for references firstnulas
.Method #2: Iterating over the keys or values using a For-Each loop.
If you only need either the keys or the values you can use
keySet
orvalues
instead ofentrySet
.This method gives a slight performance advantage over iteration
entrySet
(about 10% faster) and is cleaner.Method #3: Iterating using
Iterator
.Using Generics:
Without Generics:
You can also use the same technique to iterate over
keySet
orvalues
.This method may seem redundant but it has its advantages. First of all it is the only way to iterate over maps in older versions of java. Another important feature is that this is the only method that allows you to remove entries from the map during iteration using
iterator.remove()
. If you try to do this with a For-Each iteration you will get "unpredictable results" according to the JavaDoc.From a performance point of view this is the same as a For-Each iteration.
Method #4: Iterating over keys and looking for values (inefficient).
This would seem to be a cleaner alternative to method #1 but in practice it is very slow and inefficient getting values by key could be very time consuming (this method in different implementations of
Map
is 20%-200% slower than method #1). If you have FindBugs installed, it will detect it and warn you of an inefficient iteration. This method should be avoided.Conclusion:
If you only want keys or values use method #2. If you are stuck on some old version of java (less than 5) or plan to remove entries during iteration use method #3. Otherwise use #1.
The interface
Map
(implemented byHashMap
) has an entrySet() method which returns a view of the Map asSet
. And thoseSet
are iterables:Please note that the one
Set
returned byentrySet()
is not a copy. It is backed by it,Map
so all changes made to one will affect the other.This also means that, in case of multi-threaded applications, you have to be careful not to modify the
Map
while iteratingSet
in this way.It is also possible to iterate an instance of
java.util.Map
with the help of thekeySet
. This method returns an instance ofjava.util.Set
, which is a view of the map. Any change to it will affect the map.Code :
Output :
In my opinion, on many occasions the following code is more intuitive and practical: