Examples of forEach and with Lambda Expression in Java 8 ?

forEach() is a method defined under Iterable interface and it is used to iterate the elements just like iterator and do many actions. forEach() got introduced to java in Java 8.

Java 8 : forEach Supports :

  1. All Collection Classes (List, Set, Map)
  2. Stream (forEach(), forEachOrdered)

1. Java 8 – forEach with Collections – List Example :

Below is the example to iterate the List using Regular Iteration.

//Regular itereator listiterator
    List<Integer> listIter =new ArrayList<Integer>();
    listIter.add(101);
    listIter.add(110);
    listIter.add(102);
    Iterator<Integer> i =listIter.listIterator();
    while(i.hasNext()) {
        System.out.println("List iterator :: "+i.next());
    }

Output :

List iterator :: 101
List iterator :: 110
List iterator :: 102

Below is the example to iterate the List using forEach()

//Iterating list through forEach
List<Integer> list =new ArrayList<Integer>();
list.add(101);
list.add(110);
list.add(102);
list.forEach(listData -> System.out.println("List forEach :: "+listData));

Output :

List forEach :: 101
List forEach :: 110
List forEach :: 102

2. Java 8 – forEach with Collections Set :

The Below example represents how to implement the forEach() with Collection Set.

Example for Regular iterations with Collections Set.

Set<Integer> setIter =new HashSet<Integer>();
setIter.add(501);
setIter.add(510);
setIter.add(502);
Iterator<Integer> i2 =setIter.iterator();
while(i2.hasNext()) {
	System.out.println("Set iterator :: "+i2.next());
}		

Output :

Set iterator :: 501
Set iterator :: 502
Set iterator :: 510

Iterating the Set using forEach()

Set<Integer> setForEach =new HashSet<Integer>();
setForEach.add(501);
setForEach.add(510);
setForEach.add(502);
setForEach.forEach(listData -> System.out.println("Set forEach :: "+listData));

Output :

Set forEach :: 501
Set forEach :: 510
Set forEach :: 502

3. Java 8 – forEach with Collections Map :

Examples to show on how to use forEach() in Collections Map.

Regular map iteration using listIterator().

Map<String,String> hashMapiter =new HashMap<String,String>();
hashMapiter.put("101","Hello");
hashMapiter.put("102","Everyone");
hashMapiter.forEach((key,value) -> System.out.println("Key : "+" ,Value:"+value));
for(Map.Entry<String,String> mapData :hashMapiter.entrySet() ) {
	System.out.println("Map iterator Key: "+mapData.getKey()+", value :"+mapData.getValue());
}		

Output :

Map iterator Key: 101, value :Hello
Map iterator Key: 102, value :Everyone

Iterating the Collections Map with forEach()

Map<String,String> hashMapdata =new HashMap<String,String>();
hashMapdata.put("101","Hello");
hashMapdata.put("102","Everyone");
hashMapdata.forEach((key,value) -> System.out.println("May forEach Key : "+" ,Value:"+value));

Output :

May forEach Key :  ,Value:Hello
May forEach Key :  ,Value:Everyone

4. Java 8 – forEach() and forEachOrdered() with Stream() :

java.util.stream Class has two methods known as forEach() and forEachOrdered(), Both performs the same operations whatever the stream() wants to perform, But the difference we can see is forEach() will not provide any guarantee in printing the output, it can be ordered or unordered because the iteration is random.

Whereas the forEachOrdered() guarantees the ordered output, that means the way we segregated in the input will get spotted as output.

Lets see some examples using forEach() and forEachOrdered() in java stream.

//iterating through forEach Stream
Stream<Integer> listSteam =Stream.of(4,7,1,4,9,0);
listSteam.parallel().forEach(listData -> System.out.println("forEach Steam :: "+listData));
//iterating through forEach Stream forEachOrdered
Stream<Integer> listSteam1 =Stream.of(4,7,1,4,9,0);
listSteam1.parallel().forEachOrdered(streamData -> System.out.println("forEachOrdered Steam :: "+streamData));

Output :

forEach Steam :: 4
forEach Steam :: 0
forEach Steam :: 4
forEach Steam :: 9
forEach Steam :: 1
forEach Steam :: 7
forEachOrdered Steam :: 4
forEachOrdered Steam :: 7
forEachOrdered Steam :: 1
forEachOrdered Steam :: 4
forEachOrdered Steam :: 9
forEachOrdered Steam :: 0

5. Java 8 – forEach Condition Check in Block :

So forEach() not only for iterating the elements, still you can perform the condition checks like regular loops.

Sample Code to perform condition check with a block of code.

Map<String,String> blockForEachMap =new HashMap<String,String>();
blockForEachMap.put("101","Hello");
blockForEachMap.put("102",null);
blockForEachMap.put("103","Everyone");
blockForEachMap.forEach((key,value) ->{ 
if(value != null) {
	System.out.println("May forEach Conditions Key : "+" ,Value:"+value) ; 
   }
 } );

Output :

May forEach Conditions Key :  ,Value:Hello
May forEach Conditions Key :  ,Value:Everyone

In the above sample, the Condition Check is restricted to iterate the element which has a null value.

Things to keep in Mind about forEach() in Java :

– forEach does not inherit all the properties of for loop
– forEach does not support play with non-final variable
– Might affect performance a little bit with a sophisticated code of Lamda+forEach, The JIT Compiler Can’t perform the optimization as it makes it with for-loop.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *