I
I
Ilya Balabanov2015-11-12 00:19:19
Java
Ilya Balabanov, 2015-11-12 00:19:19

How to properly use lambda expressions in Java?

Good evening everyone! There is some code that uses lambda expressions.

public class Calculator {

     interface IntegerMath {

        int operation(int a, int b);
    }

     int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }

    public static void main(String... args) {
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = "
                + myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = "
                + myApp.operateBinary(20, 10, subtraction));
    }
}

Similarly, it is necessary to implement finding max, min, sum, count. I know that you can use SummaryStatistics for this, but I need it through these expressions. Here's what I have:
public class Solution2 {
    
    interface RandomDouble {
        double operation(double[] numbers);
    }
    
    public double operateBinary(double[] numbers, RandomDouble op) {
        return op.operation(numbers);
    }
    
    public static void main(String[] args) {
        Solution2 myApp = new Solution2();
//        RandomDouble sum
//        RandomDouble max
//        RandomDouble min
        System.out.println("Sum: " + myApp.operateBinary(numbers, sum));
        System.out.println("Min: " + myApp.operateBinary(numbers, min));
        System.out.println("Max: " + myApp.operateBinary(numbers, max));
    }
}

I don't know how to write the expression itself. How to implement this and is it possible? Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Vitrenko, 2015-11-12
@ilyablbnv

Just don't understand the syntax?

public static void main(String[] args) {
        Solution2 myApp = new Solution2();
        double[] numbers = new double[10];
        RandomDouble sum = (arr) -> {  double forSum = arr[0]; return forSum; };
        RandomDouble min = (arr) -> { double forMin = arr[0]; return forMin; };
        RandomDouble max = (arr) -> {  double forMax = arr[0]; return forMax; };
        System.out.println("Sum: " + myApp.operateBinary(numbers, sum));
        System.out.println("Min: " + myApp.operateBinary(numbers, min));
        System.out.println("Max: " + myApp.operateBinary(numbers, max));
    }
}

Or do you not understand the algorithm how to find the sum? :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question