Foreach method in Java 8
This blog post is about foreach method in Java 8. This method is used to iterate over collections. The main use I found in this method is to iterate maps in Java.
Here 'usStates' is the name of the map. This syntax is slightly difficult to remember. Using foreach method, we can iterate the map as follows;
This is explained in a program as shown below:
The output of the program is as follows:
The normal syntax used in iterating a map in Java is as follows:
for (Map.Entry<String, String> entry : usStates.entrySet())
Here 'usStates' is the name of the map. This syntax is slightly difficult to remember. Using foreach method, we can iterate the map as follows;
usStates.forEach((k,v)->{ //Easy to iterate the map
This is explained in a program as shown below:
import java.util.HashMap; import java.util.Map; public class ForEachMap { public static void main(String a[]) { Map<String, String> usStates = new HashMap<>(); usStates.put("California", "Sacramento"); usStates.put("Kansas", "Topeka"); usStates.put("New York", "Albany"); usStates.put("Pennsylvania", "Harrisburg"); usStates.put("Florida", "Tallahassee"); // iterating the Map through normal method. System.out.println("***Iterating the map through normal method***\n"); for (Map.Entry<String, String> entry : usStates.entrySet()) { System.out.print("US State : " + entry.getKey()); System.out.print("\tCapital : " + entry.getValue()); System.out.println(); } // iterate through Map using forEach method System.out.println("\n\n***Iterating the map through foreach method***\n"); usStates.forEach((k,v)->{ //Easy to iterate the map System.out.print("US State : " + k); System.out.print("\tCapital : " + v); System.out.println(); }); } }
The output of the program is as follows:
***Iterating the map through normal method*** US State : New York Capital : Albany US State : California Capital : Sacramento US State : Kansas Capital : Topeka US State : Florida Capital : Tallahassee US State : Pennsylvania Capital : Harrisburg ***Iterating the map through foreach method*** US State : New York Capital : Albany US State : California Capital : Sacramento US State : Kansas Capital : Topeka US State : Florida Capital : Tallahassee US State : Pennsylvania Capital : Harrisburg
Comments
Post a Comment