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) {
          
          System.out.println(states);
         }
  
         // iterating the List through foreach method using lambda expression
         System.out.println("\n\n***Iterating the list through foreach method using lambda expression***\n"); 
         usStates.forEach(states->System.out.println(states));
         
         System.out.println();
         
      // iterating the List through foreach method using method reference
         System.out.println("\n\n***Iterating the list through foreach method reference***\n"); 
         usStates.forEach(System.out::println);
        
         // iterating the List through foreach method using lambda expression with a condition
         System.out.println("\n\n***Iterating the list through foreach method using lambda expression with a condition***\n"); 
         usStates.forEach(states->
         {
          //We are trying to print states which contains the word "New"
          if(states.contains("New"))
          {
           System.out.println(states);
          }
         });
  
 }

}

The output of this program is as follows:


***Iterating the list through normal method***

California
New York
New Mexico
Pennsylvania
New Jersey


***Iterating the list through foreach method using lambda expression***

California
New York
New Mexico
Pennsylvania
New Jersey



***Iterating the list through foreach method reference***

California
New York
New Mexico
Pennsylvania
New Jersey


***Iterating the list through foreach method using lambda expression with a condition***

New York
New Mexico
New Jersey

Please comment below if there is any questions.

Similar programs:

1) Java program to check if an array is bitonic
2) Java program to convert mobile number pad to characters
3) Java program to get next greater element in an array

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++