Java 8 forEach() vs Traditional Loops

💡 Why do we need forEach() in Java 8 when we already have loops? Java has always supported iteration using traditional loops. But with Java 8, forEach() was introduced to align with functional programming and stream processing. Let’s break it down 👇 🔹 1. Traditional for Loop for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } ✅ Gives full control using index ✅ Supports forward & backward traversal ✅ Easy to skip elements or modify logic ⚠️ Downside: You must manage indexes manually, which can lead to errors like ArrayIndexOutOfBoundsException ------------------------------------------------------------------------------ 🔹 2. Enhanced for-each Loop for(int num : numbers){ System.out.println(num); } ✅ Cleaner and simpler syntax ✅ No need to deal with indexes ⚠️ Limitation: Only forward iteration No direct access to index ------------------------------------------------------------------------------ 🔹 3. Java 8 forEach() (Functional Approach) Arrays.stream(numbers) .forEach(num -> System.out.println(num)); 👉 Even more concise: Arrays.stream(numbers) .forEach(System.out::println); ✅ Encourages functional programming ✅ Works seamlessly with Streams API ✅ More expressive and readable ✅ Can be used with parallel streams for better performance ------------------------------------------------------------------------------ 🔍 What happens internally? forEach() is a default method in the Iterable interface It takes a Consumer functional interface The lambda you provide is executed via: void accept(T t); ------------------------------------------------------------------------------ 🚀 Final Thought While traditional loops are still useful, forEach() brings a declarative and modern way of iterating data — especially when working with streams. #Java #Java8 #Programming #Developers #Coding #FunctionalProgramming

To view or add a comment, sign in

Explore content categories