Lambda Expressions in Java: summing numbers and finding max

Summing Numbers In this example, we have a list of numbers: 1, 2, 3, 4, and 5. We define a lambda expression Integer::sum and pass it as a BinaryOperator<Integer> to the calculate method. The lambda expression represents the sum method reference, which calculates the sum of two integers. The calculate method takes a list of numbers, an initial value, and a BinaryOperator<Integer> as arguments. It iterates over the numbers and applies the operator using the apply method, accumulating the result. Finally, it returns the calculated sum.

Finding the Maximum Number In this part of the example, we reuse the calculate method to find the maximum number in the list. We define a different lambda expression Integer::max and pass it as the operator. This lambda expression represents the max method reference, which returns the greater of two integers. Again, the calculate method iterates over the numbers, applies the operator, and keeps track of the maximum number. Finally, it returns the maximum number found.

import java.util.Arrays;
import java.util.List;
import java.util.function.BinaryOperator;

public class LambdasExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Title: Summing Numbers
        int sum = calculate(numbers, 0, Integer::sum);
        System.out.println("Sum: " + sum);

        // Title: Finding the Maximum Number
        int max = calculate(numbers, Integer.MIN_VALUE, Integer::max);
        System.out.println("Max: " + max);
    }

    private static int calculate(List<Integer> numbers, int initialValue, BinaryOperator<Integer> operator) {
        int result = initialValue;
        for (Integer number : numbers) {
            result = operator.apply(result, number);
        }
        return result;
    }
}