Assuming you have the following list:
List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f"); |
if you want to do something by using each element in a collection, there are two ways:
1)
list.forEach(s -> System.out.println(s)); |
2)
for(String s: list){ System.out.println(s); } |
Both of the above two ways print the elements in sequential:
a b c d e f
In this particular case, using lambda expression is not superior than using enhanced for loop.
The main advantage of using the forEach() method is when it is invoked on a parallel stream, in that case we don’t need to wrote code to execute in parallel.
The following code will execute in parallel:
list.parallelStream().forEach(s -> System.out.println(s)); |
The output could be:
d f a b c e
Therefore, whenever parallel execution could possibly improve the performance of the program, the forEach() method should be considered as a good option. You can always do an A/B test for your program and see which way performs better.
Which one is faster from these?
Using parallel execution does not necessary increase performance, especially if your application already multi-threaded, it just takes control of muti-threading out of your hands.