How to use closure in Java

3 Answers

0 votes
// Lambda Capturing a Variable

public class Main {
    public static void main(String[] args) {

        int x = 10;
        int y = 20;

        // A closure (lambda) that captures x and y from the surrounding scope.
        // Lambdas can capture "effectively final" variables.
        Runnable add = () -> {
            int result = x + y;
            System.out.println(result);
        };

        // Use the closure
        add.run();
    }
}


/*
run:

30

*/

 



answered Jun 2 by avibootz
0 votes
// Closure Returning a Value

import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {

        int base = 5;

        // Closure capturing "base"
        Supplier<Integer> multiplier = () -> base * 6;

        System.out.println(multiplier.get());
    }
}



/*
run:

30

*/

 



answered Jun 2 by avibootz
0 votes
// Closure Capturing and Using Parameters

import java.util.function.BiFunction;

public class Main {
    public static void main(String[] args) {

        int factor = 3;

        // Closure capturing "factor"
        BiFunction<Integer, Integer, Integer> multiply = (a, b) -> (a + b) * factor;

        System.out.println(multiply.apply(5, 5));
    }
}


/*
run:

30

*/

 



answered Jun 2 by avibootz

Related questions

4 answers 38 views
4 answers 50 views
4 answers 42 views
5 answers 45 views
4 answers 43 views
...