Let say I have an array with a thousands independent objects inside. Now I want to pass over each of them and perform the same operation, for instance, change the value of a specific field.
At first glance, there are multiple approaches in Java 8 to such task, for instance:
forEach();
with lambda expression inside:itemsArr.forEach(item -> item.setValue("test"));
forEach();
with iterator.The final result should be: 100% of array elements should have cared.
What is the optimal approach to such task?
Update:
There is a similar question but talks about another aspect, I'm interesting not in different types of loops performance comparison (while
, for
, forEach
) but in a performance comparison of threats vs. lambdas in a task of array traversal?
forEach(name -> System. out. println(name)); Since the introduction of Lambda expressions in Java 8, this is probably the most common way to use the forEach method.
Iterable forEach() The forEach() method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
forEach() and parallel foreach() is the multithreading feature given in the parallel forEach(). This is way faster that foreach() and stream.
forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.
Use a parallel stream, which the JVM will process using multiple threads:
Arrays.stream(itemsArr).parallel().forEach(item -> item.setValue("test"));
Although you seem to have a Collection, not an array, so:
itemsArr.parallelStream().forEach(item -> item.setValue("test"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With