CodeNewbie Community 🌱

Cover image for How does the "forEach" loop work in Java?
Maddy
Maddy

Posted on

How does the "forEach" loop work in Java?

Java 8 has introduced many features, and the forEach() method is one of them.

In short, it's a way to iterate over a Collection (for example, a map, a set or a list) or a Stream.

The forEach() takes only one parameter, which is a functional interface . This means that you can use a lambda expression as an argument.

Let's see some examples to understand how the forEach() works on Collections and Streams.

FOREACH() ON A LIST

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

public class Fruit {

    public static void main(String[] args) {

        List<String> listOfFruits = new ArrayList<>();
        listOfFruits.add("apple");
        listOfFruits.add("pear");
        listOfFruits.add("banana");
        listOfFruits.add("mango");

        //using a lambda expression
        listOfFruits.forEach(x -> System.out.println(x));

        //using a method reference
        listOfFruits.forEach(System.out::println);

    }
}

Enter fullscreen mode Exit fullscreen mode

The outcome in both cases is:

apple
pear
banana
mango
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we are:

  • Creating a List called listOfFruits.
  • Adding items to the list.
  • Looping through the items and printing them using a lambda expression or a method reference.

FOREACH() ON A MAP

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Fruit {

    public static void main(String[] args) {

        Map<Integer, String> mapOfFruits = new HashMap<>();
        mapOfFruits.put(1, "apple");
        mapOfFruits.put(2, "pear");
        mapOfFruits.put(3, "banana");
        mapOfFruits.put(4, "mango");

        mapOfFruits.forEach((x, y) -> System.out.println(x + " " + y));

    }
}

Enter fullscreen mode Exit fullscreen mode

The outcome is:

1 apple
2 pear
3 banana
4 mango
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we are:

  • Creating a mapOfFruits with Integer as the key and String as the value.
  • Populating the map with different fruits. For example, key 1 is linked to apple. And so on.
  • Looping through the items and printing their keys and values using a lambda expression.

FOREACH() ON A SET

import java.util.HashSet;
import java.util.Set;

public class Fruit {

    public static void main(String[] args) {

        Set<String> setOfFruits = new HashSet<>();

        setOfFruits.add("apple");
        setOfFruits.add("pear");
        setOfFruits.add("banana");
        setOfFruits.add("mango");

        setOfFruits.forEach(x -> System.out.println(x));

    }
}
Enter fullscreen mode Exit fullscreen mode

The outcome is:

banana
apple
pear
mango
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we are:

  • Creating a setOfFruits.
  • Adding fruits to the set.
  • Looping through the items and printing them using a lambda expression.

NOTE: a Set doesn't guarantee any order. Also, it doesn't accept duplicates. If you try to add another "mango", you won't get any compilation error, but it won't print out the second "mango".

FOREACH() ON A STREAM

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

public class Fruit {

    public static void main(String[] args) {

        List<String> listOfFruits = new ArrayList<>();
        listOfFruits.add("apple");
        listOfFruits.add("pear");
        listOfFruits.add("banana");
        listOfFruits.add("mango");

        listOfFruits.stream()
                .forEach(x -> System.out.println(x));
    }
}
Enter fullscreen mode Exit fullscreen mode

FOREACH() TO PRINT A FILTERED LIST OF ITEMS

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

public class Fruit {

    public static void main(String[] args) {

        List<String> listOfFruits = new ArrayList<>();
        listOfFruits.add("apple");
        listOfFruits.add("pear");
        listOfFruits.add("banana");
        listOfFruits.add("mango");

        listOfFruits.stream()
                .filter(x -> x.length() == 5)
                .forEach(x -> System.out.println(x));
    }
}

Enter fullscreen mode Exit fullscreen mode

The outcome is:

apple
mango
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we are:

  • Creating a listOfFruits.
  • Adding fruits to the list.
  • Using the Stream API to filter out those fruits whose length is equal to 5.
  • Looping through the filtered list and printing the items using a lambda expression.

FOREACH() vs FOREACHORDERED()

If you want to ensure that the items are printed in order, you can use the forEachOrdered() method. This method is a terminal operator. The forEach() always goes at the end of a Stream because there is nothing to return after its execution. The same goes for the forEachOrdered() method.

Let's look at an example to understand this better:

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

public class Fruit {

    public static void main(String[] args) {

        List<String> listOfFruits = Arrays.asList("apple", "mango", "pear", "banana");

        //using forEach()
        listOfFruits.stream().parallel().forEach(System.out::println);
        System.out.println("-------------------");
        // using forEachOrdered()
        listOfFruits.stream().parallel().forEachOrdered(System.out::println);

    }
}

Enter fullscreen mode Exit fullscreen mode

The outcome is:

pear
banana
apple
mango
-------------------
apple
mango
pear
banana
Enter fullscreen mode Exit fullscreen mode

WHAT IS THE DIFFERENCE BETWEEN A FOREACH() AND A FOREACHORDERED()?

When using parallelism (in short, when things run simultaneously) on a forEach(), the order of items is not guaranteed. The forEachOrdered() is a way to explicitly say that you want to maintain the order of encounter, and indeed the items are printed that way.

WHAT ARE THE ADVANTAGES OF USING A FOREACH() LOOP?

✅ The code is more readable: if you compare the forEach() with a regular for loop, the forEach() is more readable and concise because you don't have to declare the initialization, condition and the increment or decrement.

✅ It's bug-free.

I hope you've found this article useful! Until next time. 😊

Top comments (8)

Collapse
 
sjain profile image
surbhi nahta

JAVA is an exceptional totally steady programming language. It is the speediest making and secure programming language. Seen by Oracle, this language is used on 3 billion contraptions from one side of the world to the other, meaning java will happen for eternity. JAVA is used to make web applications, games, more modest applications, business protests, etc. There is a wide level of JAVA as it will in regular be used in the advancement of an endeavor.
Job Oriented Java Certification Course in Pune

Collapse
 
ronald3tolkien3 profile image
Ronald3Tolkien3

Students, I know you are looking for a reliable essay writing service to cover your back. I would like to recommend proessays.net to everyone who wants to be sure about their grades. These guys never failed me after over ten orders so far. They’re excellent!

Collapse
 
grenmonika923 profile image
grenmonika923

I know that students very often do not cope with their assignments, and there are explanations for this. In my opinion, students are loaded with various academic tasks and therefore are not able to complete everything on time and at the same time get a high score for their work. I often use essayshark.com custom essay writers and I believe it has helped me survive in many ways while maintaining a high grade. While the Internet provides many academic writing service providers that can help students, I only trust a trusted resource. This resource is available 24/7, and I place an order when it suits me. I am sure that the experience of communicating with professionals helps me in my studies, and I never cease to be surprised by the high quality of experts.

Thread Thread
 
karas1 profile image
Karas

Sometimes, finding top-notch essays can seem like a time-consuming and expensive endeavor. However, there are a number of reliable resources and services writepaper.com/custom-essay custom essay writing services , where you can find excellent essays at reasonable prices. Academic writing experts offer quality essays that meet your requirements and budget. These papers created by professionals will help you successfully cope with your academic workload

Collapse
 
checwilliam profile image
checwilliam

For me, writing a thesis was not easy, because the whole process of writing required not only the correct knowledge of the chosen topic, but also a thorough study of background information. It all takes a lot of time and effort. For me, the master thesis writing service allowed me to provide the professor with better content. In the process of cooperation, a personal writer was assigned to me, the chat with which was securely protected and this excluded the possibility of confidentiality violation. I am confident in this resource and recommend it to my friends. I enjoyed working in collaboration with professionals in my field, and this gave me the opportunity to reduce the load and create a quality context that was highly appreciated by the teachers and received a high score.

Collapse
 
cambridgejessy profile image
cambridgejessy

The forEach() loop in Java is a way to iterate over Collections and Streams using lambda expressions. It's a powerful feature introduced in Java 8, which simplifies iteration and processing of data. It's commonly used in capstone projects for efficient data processing.

Collapse
 
iteducationcentre1 profile image
iteducationcentre1

Thanks for the post.
also, check Java training in Nagpur

Some comments may only be visible to logged-in visitors. Sign in to view all comments.