Home Page Java Index

Java Storing Function in Variable

We will first create a normal implementation of lambdas and then create a program that use a variable that contains a function.


package com.Kruger.bdg;

import com.sun.tools.javac.util.List;

public class Main {

    public static void main(String[] args) {

        List.of( 1, 2, 3, 4, 5, 6, 7, 8 ).stream()
                .filter(r -> r%2 == 0)
                .map( x -> x * x)
                .forEach(val -> System.out.println(val));

    }
}

Now we will create a variable that contains function r -> r%2 == 0.

The following is when using IntelliJ. Highlight the above mentioned peace of code, right click, refactor, extract, variable.
Below is the generated code. You can see that a variable integerPredicate was generated and also replaced the
peace of code r -> r%2 == 0. One can changed the function a bit and create a new variable.

// This will be true when odd Predicate
Predicate integerPredicateNo2 = r -> r % 2 == 1;


package com.Kruger.bdg;

import com.sun.tools.javac.util.List;
import java.util.function.Predicate;

public class Main {

    public static void main(String[] args) {

        // This is the variable that has been created that contians the function
        Predicate integerPredicate = r -> r % 2 == 0;

        List.of( 1, 2, 3, 4, 5, 6, 7, 8 ).stream()

                // r -> r%2 == 0 have been replaced with integerPredicate.
                .filter(integerPredicate)
                .map( x -> x * x)
                .forEach(val -> System.out.println(val));

    }
}