My advice would be:
-
Use the style that you and your coworkers agree is most maintainable.
-
If you and your colleagues are not yet comfortable with lambdas, keep learning.
-
Don’t obsess over performance. It is often not the most important thing.
Generally speaking, lambdas and streams provide a more concise and (once everyone is up to speed) more readable way of expressing this kind of algorithm. Performance is not the primary goal.
If performance does become an issue, then the standard advice is to code, test, benchmark, profile and optimize. And do it in that order! You can easily waste a lot time by optimizing at the coding stage, or by optimizing code that has minimal impact on overall application performance.
- Let the application benchmarks tell you if you need to optimize at all.
- Let the profiler point out the parts of your code that are worthy of the effort of optimization.
In this specific example, the performance difference is going to be too small to measure. And if you scaled up to a list of millions of elements, the performance will be dominated by the time taken to build the list and write the numbers. The different ways of iteration will only contribute a small part to the overall performance.
And for folks, who (despite all of the above) still want to know whether it is faster to use a lambda or a conventional loop, the best general answer is:
“It depends on all sorts of factors that 1) are not well understood, and 2) liable to change as Java compiler technology evolves.
We could give you an answer for a specific example with a specific Java major/minor/patch release, but it would be unwise to generalize.