Java Lambda

Lambda is a short block of code that is a function do not have a name

Daniel Liu
Dev Genius

--

Overview

Lambda was added to Java in version 8. Similar to Python lambda is a short block of code that is a function do not have a name. Like functions they can take in arguments and returns a value. Unlike Pythons lambda Java has its own way of using lambda. Like in Python lambda functions are typically used in higher order functions or functions that take in another function as an argument.

Photo by Markus Spiske on Unsplash

Implementation

To use lambda you start by declaring the argument separated by -> then the function definition.

// argument -> definition
x -> System.out.println(x)

If the lambda function takes in more than 1 argument or not argument it needs a parenthesis.

(x, y) -> x + y
() -> System.out.println("hi")

If the lambda function is more than one line you can use curly braces to wrap the definition but if it is supposed to return a value be sure to add that.

(x, y) -> {
System.out.println("x: " + x);
System.out.println("y: " + y);
return x+y;
}

Assigning

To assign a lambda function to a variable you have to declare the variable using the Consumer key word. The generic declares what type of argument the function will take.

Consumer<Integer> display = x -> System.out.println(x);

This can be used by higher order method as is.

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
Consumer<Integer> display = x -> System.out.println(x);
numbers.forEach( display );
>> 1
>> 2
>> 3
>> 4

To use the Consumer method outside of a higher order function you will have to use the accept method.

Consumer<Integer> display = x -> System.out.println(x);
display.accept(1);
>> 1

Conclusion

Using lambda helps reduce lines of code and makes use of Java’s built in higher order function. It is also used in functional programming and is more efficient as well. Overall while it is not necessary to use lambda it helps keep code readable.

--

--