JAVA-Four (4) ways to Iterate through Java Map



There are 4 ways you can iterate through List.


  • Advanced for loop
  • Iterating over keys or values using keySet() and values() methods
  • Iterator
  • Collections’s stream() util (Java8)


Java Example:



package com.knowledgefactory;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
 * @author www.knowledgefactory.net
 */
public class KnowledgeFactoryIterateThroughMap {
public static void main(String[] argv) {
// create list
Map<Integer, String> knowledgefactorymap = new HashMap<>();
// add 5 different key/values to map
knowledgefactorymap.put(1, "Java");
knowledgefactorymap.put(2, "Scala");
knowledgefactorymap.put(3, "Kotlin");
knowledgefactorymap.put(4, "Go");
knowledgefactorymap.put(5, "Python");
// iterate via Advanced for loop
System.out.println("\n==> Advance For Loop Example..");
for (Map.Entry<Integer, String> entry : knowledgefactorymap.entrySet()) {
System.out.println(entry);
}
// iterate via "iterator loop"
System.out.println("\n==> Iterator Example...");
Iterator<Map.Entry<Integer, String>> it = knowledgefactorymap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> pair = (Map.Entry<Integer, String>) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
// Iterating over keys or values using keySet() and values() methods
System.out.println("\n==> Iterating over keys or values using keySet() and values() methods...");
// using keySet() for iteration over keys
for (Integer key : knowledgefactorymap.keySet())
System.out.println(key);
// using values() for iteration over keys
for (String value : knowledgefactorymap.values())
System.out.println(value);
// From Java 8:collection stream() util
System.out.println("\n==> collection stream() util....");
knowledgefactorymap.forEach((k, v) -> System.out.println(k + "=" + v));
}
}



Output:



==> Advance For Loop Example..
1=Java
2=Scala
3=Kotlin
4=Go
5=Python

==> Iterator Example...
1 = Java
2 = Scala
3 = Kotlin
4 = Go
5 = Python

==> Iterating over keys or values using keySet() and values() methods...
1
2
3
4
5
Java
Scala
Kotlin
Go
Python

==> collection stream() util....
1=Java
2=Scala
3=Kotlin
4=Go
5=Python



This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Comments