What are Lambdas in Java?

In general a lambda expression is an anonymous function, which means for some combination of inputs, there is a specific output. In the context of Java, a lambda expression is a kind of anonymous method with a more compact constructor syntax. Lambdas in Java are first class citizens, and can be passed as method parameters (as a Functional Interface).

Lambdas are also popular in languages like Go, Clojure, and Swift.

Lambda Expression Syntax

For those that have never worked with lambdas before, their appearance can seem strange. Especially for Java developers. Here are some major points to know about lambda expression syntax:

  • • Java lambda syntax is as follows: (parameters) -> {statements}
  • • Lambdas can have 0 or more parameters
  • • Lambda parameter types can be declared or inferred
  • • Lambdas without parameters are indicated by using empty parentheses ()
  • • If a lambda has only has 1 parameter, the parentheses () can be omitted
  • • The expression/body of a lambda function can contain 0 or more statements
  • • If a lambda expression contains a single statement, curly braces {} can be omitted
  • • If a lambda expression only contains a single statement and curly braces are omitted, the return keyword is not necessary, and the return type will match the result of the expression

Lambda Expression Examples

Do Lambda Expressions have a Type?

Unlike other languages with lambdas, Java lambdas expressions are a subclass of Object, and an instance of a functional interface (an interface with a single abstract method).

Functional interfaces can be referred to as lambda target types. In order for a lambda expression to be tied to a specific target type, it must have the same parameter and return types. This means that the same lambda expression can be tied to different target types, as long as the input parameters and return types match.

One thought on “What are Lambdas in Java?”

  1. Pingback: What is a Java Functional Interface? - Big Datums

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">