Java lambda expressions simple examples

Several simple and useful lambda expressions in Java:

  • no parameters: () -> 'x'
  • one parameter: odd -> odd % 2 != 0;
  • two parameters: (a, b) -> a + b;
  • mutliple parameters: (a, b, c) -> a^2 + b^2 = c^2;

Short video tutorial: java lambda expressions simple examples

Simple lambda expression

The simplest lambda expressions that I can think of are without input or output parameters:

() -> 'x'

example using Runnable:

Runnable runner = () -> {
    System.out.println("Using lambda expression in java!");
};
runner.run();

result:

Using lambda expression in java!

You can use interface only with output parameter by using Consumer:

Callable<Boolean> call = () -> {
    System.out.println("lambda no parameters");
    return false;
};
System.out.println(call.call());

result:

lambda no input parameters
false

Lambda expression with one parameter

You can provide one parameter to lambda expression by using:

Function<Integer, Boolean> 

The first parameter is input and the second one is output!

example checking number is it odd or even:

Function<Integer, Boolean>  r = odd -> odd % 2 == 0;
System.out.println(r.apply(6)+ " " + 6);

or a longer version:

Function<Integer, Boolean> isOdd = (Integer a) -> {
    if (a % 2 == 0) {
        return true;
    } else {
        return false;
    }
};
System.out.println(isOdd.apply(6) + " " + 6);

result:

true 6

Another example checking if character is a vowel letter:

List<Character> listOfVowels = Arrays.asList('a', 'e', 'i', 'o', 'u', 'y');

Function<Character, Boolean> isVowel = c -> listOfVowels.contains(c);
System.out.println(isVowel.apply('a') + " " + 'a');
System.out.println(isVowel.apply('b') + " " + 'b');

result:

true a
false b

Note: if you get error like:

Operator '+' cannot be applied to '', 'int'

It means that you are not providing the correct interface or parameters for your lambda expression. For example this code will give error:

Runnable  r = odd -> odd + 2 == 0;
System.out.println(r.apply(6));

because of interface Runable. Use instead to avoid the error: Function<Integer, Boolean>

Lambda expression two parameters

You have several options if you want to use lambda expression with two arguments. Here we will have a look on two:

  • BiFunction
  • BinaryOperator

The first example is lambda for string concatenation:

BiFunction concat = (Object a, Object b) -> {
    System.out.println(a.toString() + b);
    return true;
};
System.out.println(concat.apply("Java", "lambda"));

result:

Javalambda
true

The second example is calculating the sum of two numbers:

BinaryOperator<Integer> sum = (a, b) -> a + b;
System.out.println(sum.apply(5, 7));

result:

12

Lambda expression in Java with more parameters

If you want to use lambda expression with more than two parameters then you need to functional interface with the number of your parameters. Example showing how to check three numbers for pytagoras triple:

You need to define an interface:

@FunctionalInterface
interface FunctionMore<One, Two, Three, Six> {
    public Six apply(One one, Two two, Three three);
}

and the to use it:

FunctionMore<Integer, Integer, Integer, Boolean> pytagorasTriple = (a, b, c) -> {
    double res = Math.sqrt((a * a) + (b * b));
    if (res == c) {
        return true;
    } else {
        return false;
    }
};
System.out.println(pytagorasTriple.apply(3 , 4, 5) + " " +  "3^2 + 4^2 = 5^2");

result:

true 3^2 + 4^2 = 5^2
false 2^2 + 4^2 = 5^2

As you can see the last parameter is output. The first three are inputs. So the lambda expression takes only 3 parameters and return one. You are free to define as much you need.

why and where to use lambda expression

Lambda expressions improve code to be more concise and readable. Lambda can be considered as inline or anonymous functions which cut down verbosity of Java code. Lambda functions derived from functional programming. In Java lambda expression is defined by three components:

  • a set of parameters
  • a lambda operator (->)
  • a function body.

For example the famous program for printing a pyramid:

public static void pyr(int n) {
    for (int i = 1; i <= 5; i++) {
        for (int j = 0; j < i; j++) {
            System.out.print("*");
        }
        //generate a new line
        System.out.println("");
    }
}

can be shorten as with lambda expression and for each:

public static void pyra(int n) {
    IntStream.range(0, n + 1).forEach(
            k -> {System.out.println(new String(new char[k]).replace("\0", "*"));}
    );
}

Used imports in the code

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;

Related Article