I understand with lambda expression(LE) we can save few lines of coding like object creation for functional interface. Also LE will be more readable. But i am sure that this is not the main reason this feature is provided for. I search it on google for Why Lambda expression in java
and i found this interesting quote at this article
Prior to Java 8, processing the elements of any collection could be done by obtaining an iterator from the collection and then iterating over the elements and then processing each element. If the requirement is to process the elements in parallel, it would be done by the client code. With the introduction of Stream API in Java 8, functions can be passed to collection methods and now it is the responsibility of collection to process the elements either in a sequential or parallel manner. -
To me this looks like the advantage of streaming api not LE. Even if LE was not provided developer could have achieved the same with creation of anonymous Consumer class. The only advantage here i can see in favour of LE is developer does not have to remember object of which functional interface needs to be created. So it takes java towards functional programming where dev is saying apply this function and he does not care about object(let jvm handle this).
Is this the main advantage of LE or there is another one major than this ?
Update :-
I tried below simple program where i tried to measure the performance parallel processing with lambda expression. Found that it took 84 unit of time with parallel processing and only 4 unit for sequential. Is it because program is not big enough and also thread overhead may be playing its role here ? May be advantages can be visible in larger function ?
public class Java8Tester {
final static String salutation = "Hello! ";
public static void main(String args[]){
List<String> stringList = new ArrayList<String>();
for(int i=0;i <100;i++){
stringList.add("Hello1");
stringList.add("Hello2");
}
long startTime = System.currentTimeMillis();
System.out.println(startTime);
stringList.parallelStream().forEach((string) -> {System.out.println("content is " + string);
});
long stopTime = System.currentTimeMillis();
System.out.println(stopTime);
System.out.println("time taken in parallel processing" + (stopTime - startTime)); // took 84 units of time
startTime = System.currentTimeMillis();
System.out.println(startTime);
for(String str : stringList ) {
System.out.println("content is " + str);
}
stopTime = System.currentTimeMillis();
System.out.println(stopTime);
System.out.println("time taken in sequential processing" + (stopTime - startTime)); // // took 4 units of time
}
}