EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials Java 8 Tutorial Java 8 forEach
 

Java 8 forEach

Updated February 14, 2023

Introduction to Java 8 forEach

The foreach method in Java 8 is used to iterate over the elements. This method is defined in the stream and iterable interfaces. This is the default method defined in the iterable interface. Collection classes extend the iterable interface, which is used to iterate the elements in a foreach loop. The foreach method in Java 8 accepts a single parameter from the functional interface, allowing us to pass a lambda expression.

 

 

Java 8 forEach

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Key Takeaways

  • From version 8, Java provides the foreach method; before version 8, this method did not exist in Java. The elements are iterated using this method.
  • The foreach method in Java is a default method that we define in iterable interfaces.

What is Java 8 forEach?

It is a utility function that was used in iterating the function onto the collection, such as a stream where we were performing the action on every element for the specified collection. The java foreach method was introduced in java 8. This method provides a concise way for the programmer to iterate over the collection. In Java 8, the foreach method performs the specified action on each element of an iterable object until all elements are processed, or the action throws an exception. Basically, this method is used to create loops in the same way that for loop is.

Why Use Java 8 forEach?

The foreach method in Java 8 provides a simple new way for java developers to iterate over lists, sets, maps, and streams. As we know, the java interface of the collection is iterable by using its super interface, and this interface contains the new API that began with java 8, in which we put the foreach state, which performed a given action for every element that was iterable until all of the elements were processed, or the action threw an exception. The foreach method in Java is essential for iterating over the elements. This method takes action on each element in the stream.

Examples of Java 8 foreach()

The below examples show java 8 foreach as follows:

Example #1

In this example, we are creating class name as foreach_java as follows. In that, we are declaring the main method. In the below example, we can see that we are defining the number in an array list; at the time of defining the number we are not using order, but in output, we can see that number is displayed in descending order as follows.

Code:

import java.util.*;
class foreach_java{
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(12, 14, 16, 18, 10);
list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
}
}

Output:

Java 8 forEach - Class name

Example #2

In the below example, we are performing the operation of each element by using a string stream as follows. We are importing the package name as java util. Also, we are defining the class name as foreach_java. In the below example, we can see that we are defining the string array in a list.

Code:

import java.util.*;
class foreach_java {
public static void main(String[] args)     {
List<String> list = Arrays.asList("Java", "for",
"each", "method");
list.stream().forEach(System.out::println);
}
}

Output:

Java 8 forEach Element

Example #3

At the time of performing print operation on every element by using reversely sorted string stream, at the same time, we are using foreach method in java. In the below example, we are importing java util and java stream packages. After importing packages, we are creating a class name as foreach_java. In java class, we are creating the main method, and in the main method, we are writing our actual code as follows. We are using the stream method to display the output of the string as follows.

Code:

import java.util.*;
import java.util.stream.Stream;
class foreach_java {
public static void main(String[] args)     {
Stream<String> stream = Stream.of("java", "for",
"each", "method");
stream.sorted (Comparator.reverseOrder())
.flatMap (str -> Stream.of(str.charAt (1)))
.forEach(System.out::println);
}
}

Output:

Stream method

Example #4

In the below example, we are defining the signature interface of the iterable method. We are importing the java util package. After importing packages, we are creating a class name as foreach_java. In java class, we are creating the main method, and in the main method, we are writing our actual code as follows. We are declaring the string one by one. We are not declaring strings in a single line.

Code:

import java.util.ArrayList;
import java.util.List;
public class foreach_java
{
public static void main(String[] args)
{
List<String> st = new ArrayList<String>();
st.add ("java");
st.add ("for");
st.add ("each");
st.add ("method");
st.forEach (str_obj -> System.out.println(str_obj));
}
}

Output:

Java 8 forEach - Signature Interface

Method

Each method is performing the given action for every element for iterable until all elements are processed and throws an exception. In the below example, we are a consumer interface with the foreach method. The consumer interface is a functional interface that accepts a single input and returns zero results. In the below example, we are creating the class name as foreach_java, in that class, we are defining the main method, and in the main method, we are writing the code of the foreach method and consumer interface.

Code:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class foreach_java {
public static void main(String[] args){
List<String> st = new ArrayList<>();
st.add("java");
st.add("for");
st.add("each");
st.add("method");
st.forEach(new Consumer<String>() {
@Override
public void accept(String name) {
System.out.println(name);
}
});
}
}

Output:

Java 8 forEach - Action for element

In method we are also using the lambda expression. Lambda expression is used primarily to define the inline implementation for an interface that was functional. We are creating the lambda expression by using the lambda operator. In the below example, we are importing the package name as util and creating the class name as foreach_java as follows.

Code:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class foreach_java {
public static void main(String[] args){
List<String> st = new ArrayList<>();
st.add("java");
st.add("for");
st.add("each");
st.add("method");
st.forEach((String name) -> {
System.out.println(name);
});
}
}

Output:

Importing the package name

The below example shows java 8 for each method by using a map as follows. We are using the hash map as follows.

Code:

import java.util.HashMap;
import java.util.Map;
public class JavaForEachMap {
public static void main(String[] args){
Map<String, Integer> st = new HashMap<>();
st.put("java", 13);
st.put("for", 12);
st.put("each", 14);
st.put("method", 19);
st.forEach((k, v) -> {
System.out.printf("%s : %d%n", k, v);
});
}
}

Output:

Java 8 forEach 7 - hashmap

The below example shows the java 8 foreach method. We are using a set with the foreach method as follows.

Code:

import java.util.HashSet;
import java.util.Set;
public class foreach_java {
public static void main(String[] args){
Set<String> st = new HashSet<>();
st.add("java");
st.add("for");
st.add("each");
st.add("method");
st.forEach((e) -> { System.out.println(e); });
}
}

Output:

Java 8 forEach 8

The below example shows the method, we are using an array with the foreach method as follows.

Code:

import java.util.Arrays;
public class foreach_java {
public static void main(String[] args){
int[] no = { 23, 24, 32, 11, 46, 37 };
Arrays.stream(no).forEach((e) -> { System.out.println(e); });
}
}

Output:

Array method

Conclusion

The function is a utility function that was used in iterating the function onto a collection, such as a stream where we were performing the action on every element for the specified collection. The foreach method in Java 8 is used to iterate the elements; this method is defined in the stream and iterable interfaces. This is the default method that we defined in the iterable interface.

Recommended Articles

This is a guide to Java 8 forEach. Here we discuss the introduction, use, and examples of Java 8 forEach and method respectively. You may also look at the following articles to learn more –

  1. Deleting Email in Java
  2. Forwarding Email in Java
  3. Receiving Email in Java
  4. Java Microservices

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW