Tuesday 9 April 2019

Java 8 forEach method with examples

        In this post, we will discuss or learn how to iterate the Map, List and Stream in java 8 using forEach method. I have given some sample examples of each collection.


  • Java 8 forEach method to iterate List

The below example is to iterate the list using foreach method and lambda expression in java 8.

package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Java8forEach {
     public static void main(String[] args) {
  
             List<String> list = new ArrayList<String>(Arrays.asList("A", "B", "C"));
  
             //Java 7, to iterate the above list
             for (String str : list) {
                   System.out.println(str);
             }
  
             //java 8, foreach method to iterate list
             list.forEach(str -> {System.out.println(str);});
     }

}

If you see the above example, you can reduce the code in Java 8 compared to earlier versions of Java.


  • Java 8 forEach method to iterate Map
In Java 8, you can iterate the map using Map.forEach(action) method and lambda expression. 

package com.test;

import java.util.HashMap;
import java.util.Map;

public class JavaforEachMap {
 
      public static void main(String[] args) {
  
           Map<Integer, String> map = new HashMap<Integer, String>();
           map.put(1, "Dell");
           map.put(2, "HCL");
           map.put(3, "Toshiba");
  
           //Java 7(earlier versions), iterate a Map
           for (Map.Entry<Integer, String> entry : map.entrySet()) {
                System.out.println("Key - "+entry.getKey() +" Value - "+entry.getValue());
           }
  
           //Java 8, iterate Map using forEach() method and lambda expression
           map.forEach((k,v) -> {
                System.out.println("key - "+k + " Value - "+v);
           });
     }

}


  • Iterate a List using Stream API and forEach() method

        In java 8, java.util.Stream represents a stream on which one or more operations can be performed. Stream operations are either intermediate or terminal. Stream terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. a java.util.Collection like lists or sets (maps are not supported). Stream operations can either be executed sequential or parallel.

      Compare java 7 and earlier versions and java 8 code to iterate a list with certain conditions as follows,

package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Java8Stream {
 
      public static void main(String[] args) {
  
            List<String> list = new ArrayList<String>(Arrays.asList("abc", "bcd", "afd", "art"));

            //Java 7, to iterate list with some conditions
            for (String str : list) {
                 if (str.contains("a")) {
                       System.out.println(str);
                 }
            }
  
           //same example in java 8 using foreach() and stream api
           list.stream().filter(a -> a.contains("a")).forEach(str -> {
                 System.out.println(str);
           });
      }

}


No comments:

Post a Comment