Posts

Showing posts from 2017

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. 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.p