Monday, August 27, 2018

Java8 Top 5 forEach Examples with tutorials

java8 forEach tutorials

Java8 introduced forEach for iteration of elements - collections, Arrays, and Map. It allows the developer to iterate collections using an internal iterator. This can be used 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.

List<String> list = new ArrayList<String>();
  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 a new way of iter in the collection of objects.

Syntax

void forEach(Consumer<? super T> action);
Each element in Collections elements are applied to consumer action, forEach is passed with the class which implements Consumer. Consumer is a Functional Interface with the 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 aList of strings Created an anonymous inner class by creating an object of Consumer Interface with accept() implementation. Each element is passed to accept method and outputs nothing.
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

Lambda Expression 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 a simple to code it.
list.forEach((String name) -> {
            System.out.println(name);
        });

Method reference forEach Example

Method reference introduced in java8 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
list.forEach(System.out::println);

forEach using Lambda Expression on Map Example

Created Map with a list of key and values using forEach, display key and values using a lambda expression.
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 is
key1:value1
key2:value2
key3:value3
key4:value4

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
Set<String> set = new LinkedHashSet<>();
        set.add("one");
        set.add("two");
        set.add("three");
        set.forEach((e) -> { System.out.println(e); });
Output is
one
two
three

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.
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

Both are used to iterate the elements in a collection forEach uses an internal iterator, 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 developer has to write a code how to iterate the collection elements.

Related article


EmoticonEmoticon