Best used forEach Examples in java8 with the explanation
java8 forEach examples
Java8
introduced forEach
for iteration of elements - collections
, Arrays
, and Map
.
It allows the developer to iterate collections using an internal iterator. It uses with Lambda Expressions and Method reference.
Java 7 for each loop example
To iterate the list of strings, We have used for each enhanced iteration in java7.
import java.util.ArrayList;
import java.util.List;
public class StringArrayLoopExample {
public static void main(String[] args) throws Exception{
List<String> list = new ArrayList<>();
list.add("one"); list.add("two"); list.add("three"); list.add("four");
for (String str : list) {
System.out.println(str);
}
}
}
The output of the above code is
one
two
three
four
With java8, forEach
is introduced with a new way of iteration in the collection of objects.
java8 foreach example
here is an syntax.
void forEach(Consumer<? super T> action);
Each element in Collections elements apply to consumer
action, forEach
is passed with the class which implements Consumer
. Consumer is a Functional Interface with a single abstract method and accepts one input parameter and generates no output. Please have the other blog post about Consumer Interface tutorials and Primitive Consumer Tutorials.
forEach Consumer Examples
- Created a List of strings.
- Created an anonymous inner class by creating an object of
Consumer
Interface withaccept()
implementation. - Each element is passed to accept the method and outputs nothing.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class ForEachConsumerExample {
public static void main(String[] args) throws Exception{
List<String> list = new ArrayList<>();
list.add("one"); list.add("two"); list.add("three"); list.add("four");
list.forEach(new Consumer<String>() {
@Override
public void accept(String name) {
System.out.println(name);
}
});
}
}
This is a Consumer Functional Interface implementation example. We will see a popular way of inline implementation using Lambda expressions
How to use Lambda Expression in forEach Example
Lambda expression
is used to initiate Function interface object creation by avoiding anonymous inner class implementation.
Please have a look about Lambda expression.
The same code is rewritten using lambda expression and it is simple to code it.
import java.util.ArrayList;
import java.util.List;
public class ForEachLambdaExample {
public static void main(String[] args) throws Exception{
List<String> list = new ArrayList<>();
list.add("one"); list.add("two"); list.add("three"); list.add("four");
list.forEach((String name) -> {
System.out.println(name);
});
}
}
How to use Method reference in forEach Example
Method reference
introduced in java8 is used to call a method of a functional interface.
This is to replace lambda expression with method reference.
This is one more way of using foreach
with Method reference
import java.util.ArrayList;
import java.util.List;
public class MethodReferenceForEachExample {
public static void main(String[] args) throws Exception{
List<String> list = new ArrayList<>();
list.add("one"); list.add("two"); list.add("three"); list.add("four");
list.forEach(System.out::println);
}
}
How to use forEach using Lambda Expression on Map Example
Created Map
with a list of keys and values using forEach
, and display keys and values using a lambda expression.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) throws Exception{
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
map.forEach((k, v) -> {
System.out.println( k+":"+ v);
});
}
}
Output:
key1:value1
key2:value2
key3:value3
key4:value4
How to use forEach using Lambda Expression on Set Example
Created Set
with a list of strings. set
does not allow duplicates. Iterate and print set
elements using forEach
and Lambda
Expression
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception{
Set<String> set = new LinkedHashSet<>();
set.add("one");
set.add("two");
set.add("three");
set.forEach((e) -> { System.out.println(e); });
}
}
Output:
one
two
three
How to use forEach using Lambda Expression on Array data Example
Arrays
data can be iterated using foreach
on Array.stream() method. Finally, use a lambda expression to get the elements.
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception{
int[] numbers = { 5,9,7,3 };
Arrays.stream(numbers).forEach((e) -> { System.out.println(e); });
}
}
Output:
5
9
7
3
Difference between forEach and for-loop in java8
Both are used to iterate the elements in a collection.
forEach
uses an internal iterator, whereas for-loop uses an external iterator.
An internal iterator is built iteration provided by java. iteration logic will not handle by developers. External Iterator is the developer who has to write a code on how to iterate the collection elements.
Conclusion
In this tutorial, Learned multiple ways of iteration objects using foreach multiple ways.