[Solved] Java 8 — Lambda Expression [closed]


If you want to create a function which adds 1 to its input, the method to create that function doesn’t need an parameters… but then you need to call that function in order to execute it. I suspect you wanted:

import java.util.function.Function;

public class LambdaExpression {
    public static Function<Integer, Integer> create() {
        Function<Integer, Integer> f = x -> x + 1;    
        return f;
    }

    public static void main(String[] args) {
        Function<Integer, Integer> f = create();
        System.out.println(f.apply(5)); // 6
    }
}

If you actually want a function which adds whatever you pass to the create method (instead of always adding 1) that’s easy:

import java.util.function.Function;

public class LambdaExpression {
    public static Function<Integer, Integer> create(int addTo) {
        Function<Integer, Integer> f = x -> x + addTo;
        return f;
    }

    public static void main(String[] args) {
        Function<Integer, Integer> f = create(3);
        System.out.println(f.apply(5)); // 8
    }
}

5

solved Java 8 — Lambda Expression [closed]