For Each loop of Java 8 ..!!
?? Saral Saxena ??????
?11K+ Followers | Linkedin Top Voice || Associate Director || 14+ Years in Java, Microservices, Kafka, Spring Boot, Cloud Technologies (AWS, GCP) | Agile , K8s ,DevOps & CI/CD Expert
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.
Therefore, whenever parallel execution could possibly improve the performance of the program, the forEach() method should be considered as a good option.
forEach() is useful for the following:
- Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList() was atomic with respect to things like get or set, but was not thread-safe when iterating.
- Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.
- Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)
- Calling a single function more cleanly by using forEach() and a method reference argument (ie, list.forEach (obj::someMethod)). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.
Just a small basic demo I have shown for this..