foreach() loop vs Stream foreach() vs Parallel Stream foreach()

foreach() loop

  • Lambda operator is not used: foreach loop in Java doesn’t use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and doing any functionality that we want.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    public class GFG {
      
        public static void main(String[] args)
        {
            String[] arr = { "1", "2", "3" };
            int count = 0;
      
            String[] arr1 = { "Geeks", "For", "Geeks" };
      
            for (String str : arr) {
                System.out.print(arr1[count++]);
            }
        }
    }

    chevron_right

    
    

    Output:

    GeeksForGeeks
    

    Here operations on count are possible even being a variable outside the loop because it is in the scope of the foreach loop.

  • It can be used for all collections and arrays: It can be used to iterate all collections and arrays in Java.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    public class GFG {
      
        public static void main(String[] args)
            throws Exception
        {
      
            String[] arr = { "1", "2", "3" };
            int count = 0;
      
            String[] arr1 = { "Geeks", "For", "Geeks" };
      
            for (String str : arr) {
                System.out.print(arr1[count++]);
            }
        }
    }

    chevron_right

    
    

    Output:



    GeeksForGeeks
    
  • The return statements work within the loop: The function can return the value at any point of time within the loop. For example, if we want to print only the first 2 values of any collection or array and then we want to return any value, it can be done in foreach loop in Java. The code below is for printing the 2nd element of an array.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    public class GFG {
      
        public static String frechlop(String[] geek)
        {
            int count = 0;
            for (String var : geek) {
                if (count == 1)
                    return var;
                count++;
            }
            return "";
        }
      
        public static void main(String[] args)
            throws Exception
        {
      
            String[] arr1 = { "Geeks", "For", "Geeks" };
            String secelt = frechlop(arr1);
            System.out.println(secelt);
        }
    }

    chevron_right

    
    

    Output:

    For
    

stream().forEach()

  • Lambda operator is used: In stream().forEach(), lambdas are used and thus operations on variables outside the loop are not allowed. Only the operations on concerned collections are possible. In this, we can perform operations on Collections by single line code that makes it easy and simple to code.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import Java.util.*;
    public class GFG {
      
        public static void main(String[] args) throws Exception
        {
      
            List<String> arr1 = new ArrayList<String>();
            int count = 0;
            arr1.add("Geeks");
            arr1.add("For");
            arr1.add("Geeks");
            arr1.stream().forEach(s -> {
      
                // this will cause an error
                count++;
      
                // print all elements
                System.out.print(s);
            });
        }
    }

    chevron_right

    
    

    Note: The operation “count++” will cause an error because lambda operations do not allow any external variable operation within itself.

  • Only used to iterate collections: The stream().forEach() is only used for accessing the collections like set and list. It cannot be used for accessing arrays.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import java.util.*;
    public class GFG {
      
        public static void main(String[] args)
            throws Exception
        {
      
            String[] arr1 = { "Geeks", "for", "Geeks" };
      
            // The next line will throw error
            // as there is no such method as stream()
            arr1
                .stream()
                .forEach(s -> {
                    System.out.print(s);
                });
        }
    }

    chevron_right

    
    

  • Return statements don’t work within this loop but the function calls are very easy to call:
    The return statement within the loop doesn’t work. The same functionality of getting 2nd element cannot be done in the same forEach() method.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import Java.util.*;
      
    public class GFG {
      
        static String second(List<String> list)
        {
            list
                .stream()
                .forEach(
                    s -> {
                        // The next line will throw error
                        // as no return allowed
      
                        // if(s=="For")return s;
      
                    });
            return "null";
        }
      
        public static void main(String[] args)
            throws Exception
        {
      
            List<String> arr1 = new ArrayList<String>();
            arr1.add("Geeks");
            arr1.add("For");
            arr1.add("Geeks");
            String f = second(arr1);
            System.out.println(f);
        }
    }

    chevron_right

    
    

    Output:

    null
    

parallel foreach()

  • Works on multithreading concept: The only difference between stream().forEacch() and parrllel foreach() is the multithreading feature given in the parllel forEach().This is way more faster that foreach() and stream.forEach(). Like stream().forEach() it also uses lambda symbol to perform functions. The example proving its multithreading nature is given as follows.The output of the code will never guarantee the same order of printing strings which clearly implies the multi threaded environment.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import Java.util.*;
      
    public class GFG {
      
        public static void main(String[] args)
            throws Exception
        {
      
            List<String> arr1
                = new ArrayList<String>();
            arr1.add("Geeks");
            arr1.add("For");
            arr1.add("Geeks");
      
            arr1
                .parallelStream()
                .forEach(
                    s -> {
                        System.out.print(s);
                    });
        }
    }

    chevron_right

    
    

    Output:

    ForGeeksGeeks
    

Tabular difference

foreach() loop stream().foreach() loop parallelStream().foreach() loop
Lambda operators is not used Lambda operator is used Lambda operator is used
Can be used to access arrays and collections Can access collections only Can access collections only
The return or control statements work within the loop The return or control statements don’t work within the loop The return or control statements don’t work within the loop
No multithreading thus slow data is in sequence No multithreading thus slow data is in sequence It is multithreaded thus very fast and sequence is different


My Personal Notes arrow_drop_up

Im a final year MCA student at Panjab University, Chandigarh, one of the most prestigious university of India I am skilled in various aspects related to Web Development and AI I have worked as a freelancer at upwork and thus have knowledge on various aspects related to NLP, image processing and web

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.