If I want to traverse collections in a HashMap:
HashMap<Integer, Elemento>
) I would traverse it with aforeach()
also if I implement aIterator()
I don't understand very well the two ways to traverse it. I do not find the difference or their functions of each one to go through what I want to go through.
Element.java
package stackoverflowejemplo;
public class Elemento {
private int numeros;
private String nombre;
public Elemento(int numeros, String nombre){
this.numeros = numeros;
this.nombre = nombre;
}
public int getNumeros() {
return numeros;
}
public void setNumeros(int numeros) {
this.numeros = numeros;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String toString(){
return getNombre() +" - "+getNumeros() ;
}
}
Map.java
import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry;
public class Mapa {
public static void main(String[] args) {
HashMap<Integer, Elemento> map = new HashMap<>();
map.put(1,new Elemento(2,"hola"));
//foreach
} }
First of all, in Java it doesn't exist
for-each()
like in other languages. What exists in Java since Java 5 isenhanced for-loop
. What this statement does, behind the scenes, is use an iterator to iterate through the collection (in the case of arrays, you don't need to use an iterator).The following code that uses enhanced for-loop:
Java then translates it to:
If you want to create a class that can work with the enhanced for-loop, it is not enough for your class/interface to provide a method that allows you to obtain a
Iterator
, it must implement the interfaceIterable
. Here's an example (very simplified):With the above class, you can use the following code:
Departure:
I ensure that the elements I print have a method
toString()
. It thenforeach
ensures that if you have a methodtoString()
on the classElemento.java
in which, you will loop through the objectvalor
with the help of thellave(Key)
.or this way:
Then an iterator I can take a look here to understand how it works and the lambda expression is clearly described here .