Link to home
Start Free TrialLog in
Avatar of Manikandan Thiagarajan
Manikandan ThiagarajanFlag for India

asked on

could you please explain the advantages of lamda foreach and stream in java8

could you please explain the advantages of lamda foreach and stream in java8
Avatar of ste5an
ste5an
Flag of Germany image

There are no advantages without a target to compare with. They are just approaches to do things differently.

Please rephrase your question.
There's a good tutorial / explanation with clear code snippets on streams

HERE

which ties in how foreach works in the context.
One thing that Streams seem underequipped for, afaict anyway, is when you might want some frequency analysis of a collection.

With a List, you might want to know the number of occurrences of (the) members, or, as below, the actual indexes of frequently appearing members in the array, so in traditional code you could do something like :


import java.util.*;


class MyCollectionHandler {


Collection<String> aList;


public static void main(String[] args){

    MyCollectionHandler mine = new MyCollectionHandler();
    
    mine.aList = new ArrayList<>();
    
    int[] ia = {1,23,4,5,9,11,131,22,101,11,23,23};
    
    for(int i : ia){mine.aList.add(String.valueOf(i));}
    
    for(int i : ia){System.out.print(Collections.frequency(mine.aList,String.valueOf(i))+" ");}
    
    System.out.println();
    
    for(int i = 0;i<ia.length;i++){
    
        if(Collections.frequency(mine.aList,String.valueOf(ia[i]))>1){
            System.out.println("The position of the frequent member "+ ia[i]+" is  "+i);
        }
    }
 

}

} 

Open in new window



This might not be so straightforward using Streams, because getting hold of the index position to find out where the frequent members appear, can't be done - even with an Iterator.

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.