Posts

Showing posts with the label Java 8

Using foreach method with list in Java 8

This blog post is about using foreach method with list in Java 8. Foreach method can be used to easily iterate a list. Check my previous post to see how to iterate foreach method with map in Java 8 . The program to iterate list using foreach method is as follows: import java.util.ArrayList; import java.util.List; /* * Java program to demonstrate the use of forEach method in List */ public class ForEachList { public static void main(String[] args) { List<String> usStates = new ArrayList<>(); usStates.add( "California" ); usStates.add( "New York" ); usStates.add( "New Mexico" ); usStates.add( "Pennsylvania" ); usStates.add( "New Jersey" ); // iterating the List through normal method System.out.println( "***Iterating the list through normal method***\n" ); for (String states:usStates) { ...

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