In writing code that meets simple requirements, let's compare the case without Lambda with the case with it. Let's consider the process of preparing a list of numbers as shown below and adding up the numbers that are doubled by 100 or more. Specifications: Add up the doubles for 100 or more
number-list
final List<Integer> numbers = Arrays.asList(50, 100, 10, 400, 120, 30, 220);
For example, you can check the values in the list one by one, and if it is 100 or more, double the value and add it to total. With this kind of calculation, it is simple and easy to understand, and there seems to be no major problem. However, it is a little because the engineer's idea of "checking the numbers one by one" is sandwiched between the specifications (adding the doubled ones for 100 or more) as one way to realize it. It can be misleading code.
without-lambda.java
int total = 0;
for (Integer number : numbers) {
if (number >= 100) {
total += number * 2;
}
}
System.out.println("Total is " + total);
The total amount of code is not so different from the above. However, how to read the processing flow that can be seen from the code will change. "Filter 100 or more numbers from the list, double them, and add them up." I haven't written any code that checks one by one in a loop. It can be expressed as if the specifications (doubled by 100 or more) are described as they are. I don't think that's the case in all cases, but I think you can write code in this example that is less misleading to the requirements.
with-lambda.java
int total = 0;
total = numbers.stream()
.filter(num -> num >= 100)
.map(num -> num * 2)
.reduce(0, (base, value) -> base + value);
System.out.println("Total is " + total);
Recommended Posts