$show=/label

Java 8 Iterable.forEach() vs foreach loop with examples

SHARE:

A quick guide to differences between the Iterable.forEach() and normal forEach Loop in Java 8. Which is better to use in the JDK 8 applications.

1. Overview


In this article, you'll learn what are the differences between the Iterator.forEach() and the normal foreach loop before java 8.

First, let us write a simple program using both approaches then you will understand what you can not achieve with the java 8 forEach.

Iterable is a collection api root interface that is added with the forEach() method in java 8. The following code is the internal implementation. Whatever the logic is passed as lambda to this method is placed inside Consumer accept() method. Just remember this for now. When you see the examples you will understand the problem with this code.
default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
Java 8 Iterable.forEach() vs foreach loop with examples


forEach() can be implemented to be faster than the for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loops externally. But there are many drawbacks of using loop internally.

2. Normal forEach() Example


In the below program, We are using foreach to add a List of objects to a collection.

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

public class NormalForEachExample {

	public static void main(String[] args) {

		List<String> list = new ArrayList<>();

		for (int i = 0; i < 10; i++) {

			list.add("Item " + i + 1);
		}

		System.out.println("Normal for loop program : " + list);

	}

}
Output:

Normal for loop program : [Item 01, Item 11, Item 21, Item 31, Item 41, Item 51, Item 61, Item 71, Item 81, Item 91]

3. Another Example to iterate the List using for loop


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

public class NormalForEachListExample {

	public static void main(String[] args) {

		List<String> list = new ArrayList<>();

		list.add("one");
		list.add("two");
		list.add("three");
		list.add("four");
		list.add("five");
		
		for(String s : list) {
			System.out.println(s);
		}

	}

}
Output:

one
two
three
four
five

4. Java 8 Iterate or Stream forEach Example


Below an example on java 8 forEach() to add values to List. This approach really makes the code simple and easy to write to the developers.
import java.util.ArrayList;
import java.util.List;

public class Java8ForEachListAddExample {

	public static void main(String[] args) {

		List<String> list = new ArrayList<>();
		list.add("One");

		list.forEach((s) -> list.add(s + 1));

		System.out.println("Final list : " + list);

	}

}
Output:

Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList.forEach(ArrayList.java:1260)
	at NormalForEachExample.main(NormalForEachExample.java:11)

This code does not work as we are trying to add the values inside the forEach() method and it internally checking the mod count validation and it is failed. Hence, Thrown the ConcurrentModificationException.


So, Here java 8 forEach() does not work to add the values to list. But the normal loops works without any issues.

5. Java 8 Stream or Iterable forEach() Example to Print the values


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

public class Java8ForEachPrint {

	public static void main(String[] args) {

		List<String> list = new ArrayList<>();
		list.add("you");
		list.add("me");
		list.add("learn");
		list.add("java");

		list.forEach(value -> System.out.println(value));

	}

}
Output:

you
me
learn
java

6. Iterable.forEach() vs foreach - Drawback 1: Accessing Values inside forEach declared outside


Creating a simple program to access the String inside the forEach() method where the string is created outside forEach().


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

public class NormalForEachExample {

	public static void main(String[] args) {

		List<String> list = new ArrayList<>();
		list.add("you");
		list.add("me");
		list.add("learn");
		list.add("java");
		
		String newString = "I am newly created";

		list.forEach(value -> {
			System.out.println(value);
			newString = "I am modified";
		});

	}

}
Compile and see what is the problem here is.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Local variable newString defined in an enclosing scope must be final or effectively final

The compilation is failed because of value modification to newString variable. That means once any variable is created outside the forEach() method can not be modified.

So, this is the drawback and can not use java 8 forEach().

7. Drawback 2: Java 8 foreach return value


Let us create a simple program that needs to return a value from the forEach() loop.


First, see with the normal for loop and which works perfectly fine without any errors.

	private static boolean hasListHasValueLengh5(List<String> list) {

		for (int i = 0; i < list.size(); i++) {

			if (list.get(i).length() >= 5) {
				return true;
			}

		}
		return false;
	}
Next is to try with the forEach() method. Internally, the forEach() method takes Consumer as an argument and it just takes the parameter but does not return any value. So, technically is impossible to return a value from the forEach() method.

But, you can do with filters and other methods but you need to use the many functions for a small one.
boolean hasLength5 =list.stream().filter( value -> value.length() >=5).findFirst().orElse(null).length() > 0;
If you are new to java 8 then it is a bit difficult to understand so better not to use for simple cases.

8. Drawback 3: Can't handle checked exceptions


forEach() method can not handle the checked exceptions.

Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch or Throwables.propagate(). But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()


	list.forEach(value -> {

			if (value.length() == 2) {
				Class.forName("com.NoClass");
				throws new RuntimeException("Length should be min 3 characters");
			}
		});

This will show the compile-time error and saying can not use throws keyword.

Class.forName("com.NoClass") throws checked exception and wants to throw to the caller but lambda enforces to wrap inside try/catch block. This is also a drawback.

9. Reaming Drawbacks with Collection forEach() method


There are many other areas to consider before using the Lambdas or forEach() method

Can be executed in parallel, so must be careful before enabling the concurrent calls. So, Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.

Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new.

Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.

Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general.

10. Conclusion


In this article, We've seen the main differences between the Iterable.forEach() vs foreach methods. It is better to avoid the stream forEach() incase if you want to do validation or return some values.

It is good to go with the tradition forEach loop over the Java 8 forEeach() loop.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Iterable.forEach() vs foreach loop with examples
Java 8 Iterable.forEach() vs foreach loop with examples
A quick guide to differences between the Iterable.forEach() and normal forEach Loop in Java 8. Which is better to use in the JDK 8 applications.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_RvaognLf3y8vZdqu_MYyURDvoOqu-m4eqlmEaYEzkRPz4mFy4SXVv-Kp9TcdYIiw8rrEhTXC1nh8AyYL7hsmNplUMpcfELDDo6gfbnG2tTL4a-FutDtBFQ90N_O7NQGv9P4GBOte6fM/w640-h327/Java+8+Iterable.forEach%2528%2529+vs+foreach+loop+with+examples.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_RvaognLf3y8vZdqu_MYyURDvoOqu-m4eqlmEaYEzkRPz4mFy4SXVv-Kp9TcdYIiw8rrEhTXC1nh8AyYL7hsmNplUMpcfELDDo6gfbnG2tTL4a-FutDtBFQ90N_O7NQGv9P4GBOte6fM/s72-w640-c-h327/Java+8+Iterable.forEach%2528%2529+vs+foreach+loop+with+examples.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/08/java-8-iterable-foreach-vs-foreach-loop.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/08/java-8-iterable-foreach-vs-foreach-loop.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content