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);
}
}
The outcome in both cases is:
apple
pear
banana
mango
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));
}
}
The outcome is:
1 apple
2 pear
3 banana
4 mango
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));
}
}
The outcome is:
banana
apple
pear
mango
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));
}
}
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));
}
}
The outcome is:
apple
mango
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);
}
}
The outcome is:
pear
banana
apple
mango
-------------------
apple
mango
pear
banana
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 (9)
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
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!
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.
I completely resonate with the struggle of balancing learning new skills while managing everything else on our plates. Itβs like, every time I pick up a new programming language or try to dive deeper into something, Iβm reminded of just how much there is to learn. But at the same time, that challenge is what makes it so rewarding, right? I remember when I first started codingβevery little breakthrough felt like a huge victory, even if it was just getting a piece of code to run without errors. Itβs easy to get discouraged, especially when you hit a roadblock, but Iβve found that pushing through those tough moments is where the real growth happens. How do others stay motivated when the learning and get help from paper writing services for me? Iβd love to hear about any tips or experiences that have helped you keep going when things get tough!
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.
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
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.
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.