Writing forEach with java 8 lambda

Let’s take a simple example. It’s easier, probably, and can not be – create a list of numbers and display it on the screen through the simplest cycle:

Everyone who used Java, probably wrote such cycles – it would seem, it is impossible to come up with something simpler and more convenient. Or is it still possible? What happens in the cycle? We all know the answer – numbers are displayed one by one until the end of the list is reached. Sounds quite logical and correct, is not it? But let’s look at the problem from the other side. Here comes to mind a comparison with the person who adds the details from the designer “Lego”, scattered on the floor, into one box – his cycle is that he takes one detail, puts it in a box, looks to see if there are any other details left on the floor (there are not one hundred of them there), puts the following detail in the box, again checks whether there are any more details left, puts them back, checks again. But what hinders to take as many details as you can grasp, and throw them in a box at once?

Let’s try to move away from old habits and finally use lambdas. Here is how the same code in Java 8 might look like:

As we can see, the structure of the lambda expression can be divided into two parts: the part to the left of the “arrow” ( -> ) contains the parameters of the expression, and the part on the right is its “body”. The compiler already knows how to work with this expression, moreover – in most cases, types in lambda expressions can be omitted explicitly in the code, making the expression even more concise:

But also it not a limit – it is possible to use the operator ::  and to receive even more beautiful:


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.