Iterate Through a HashMap

In a HashMap, we can

  1. iterate through its keys
  2. iterate through its values
  3. iterate through its keys/values

Iterating Using the forEach loop.


\begin{lstlisting}
import java.util.HashMap;
import java.util.Map.Entry;
\par
cl...
...()) {
System.out.print(value);
System.out.print('', '');
}
}
\end{lstlisting}

Output


\begin{lstlisting}
HashMap : { One =1 , Two =2 , Three =3}
Entries : One =1 , Two =2 , Three =3
Keys : One , Two , Three ,
Values : 1, 2, ,3,
\end{lstlisting}

In the above program, note that we have imported the java.util.Map.Entry package. Here, Map.Entry is the nested class of the Map interface. This nested class returns a view (elements) of the map. It is also possible to iterate a HashMap using the iterator() method. In order to use this method, we must import the java.util.Iterator package.


\begin{lstlisting}
import java.util.HashMap;
import java.util.Iterator;
import j...
...out.print( iterate3.next());
System.out.print('', '');
}
}
}
\end{lstlisting}

Output


\begin{lstlisting}
HashMap : { One =1 , Two =2 , Three =3}
Entries : One =1 , Two =2 , Three =3
Keys : One , Two , Three ,
Values : 1, 2, 3,
\end{lstlisting}

In the above program, note that we have imported the java.util.Map.Entry package. Here, Map.Entry is the nested class of the Map interface. This nested class returns a view (elements) of the map.