ForEach in Java 8 with Example – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 20 Sep 2020 16:55:08 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg ForEach in Java 8 with Example – Programmerbay https://programmerbay.com 32 32 ForEach in Java 8 with Example https://programmerbay.com/foreach-method-in-java-8/ https://programmerbay.com/foreach-method-in-java-8/#respond Wed, 17 Jun 2020 10:57:02 +0000 https://programmerbay.com/?p=6435 In Java 8, forEach is introduced that provides an efficient way to iterate through collections ( List, Sets, and more) and Streams.

In Collection hierarchy, the iterable interface is the root interface in which a new feature has added namely forEach(). It allows iterating a collection of elements until the last element is processed.

It accepts consumer (functional interface) as an argument, meaning one needs to define a lambda expression that would take a single input and return nothing.

default void forEach(Consumer<? super T> action)

Functionality wise, forEach and enhanced for-loop are similar, but the new forEach is a type of internal loop. Meaning, the iterator handles iteration behind the scene, as a result, programmers don’t have to worry about the iteration behaviour.

Code Example:

Iterating over List:

import java.util.List;

public class ForEachExample {
public static void main(String[] args) {
List nameList = new ArrayList();
nameList.add("Programmer");
nameList.add("ProgrammerBay");
nameList.add("coders");

nameList.forEach(singleItem -> System.out.println(singleItem));
}
}

Output

Programmer
ProgrammerBay
coders

Iterating over Map:

import java.util.*;

public class ForEachExample {
public static void main(String[] args) {
Map nameList = new LinkedHashMap();
nameList.put(1,"Programmer");
nameList.put(2,"ProgrammerBay");
nameList.put(4,"coders");

nameList.forEach((key,value) -> System.out.println("This is my key : "+key +" and value : "+value));
}
}

 

Output:

This is my key : 1 and value : Programmer
This is my key : 2 and value : ProgrammerBay
This is my key : 4 and value : coders

Iterating over Stream of elements :

public class CreateStreams {
    public static void main(String[] args) {
        String[] stringArr = new String[]{"This", "is", "Example", "of", "Stream"};
        // Creating Stream of Array
        Stream<String> arrayStream = Stream.of(stringArr);
        arrayStream.forEach(singleString -> System.out.print(singleString + " "));
    }
}

Output:

This is Example of Stream

Point to remember about forEach:

  • Java 8, forEach is an internal loop
  • It makes code clean and more readable
  • It is less error-prone
  • It is a default method

]]>
https://programmerbay.com/foreach-method-in-java-8/feed/ 0