What are the advantages of Lambda Expressions present in Java 8?

Java 8 will be released soon (March 2014) and the main feature of this release are Lambda Expressions.

Could anyone describe, as the question says, what this feature will add in practice for developers and, if possible, some example of commented code?

Author: bfavaretto, 2013-12-13

4 answers

Lambda expressions are a common feature in many languages, in particular those that follow the paradigm Functional Programming (the term itself comes from the Lambda Calculus, mathematical foundation that supports this paradigm), but that have recently been introduced in languages of other paradigms (such as, in the case, the imperative/object-oriented). To understand them, it is necessary to know the concepts of first-class functions and literals .

Traditionally in Java, a method (function, procedure) exists only as a member of a class. This means that while you can have a variable "pointing" to an object, you cannot save a method in a variable. Everything that is allowed to reference in a language (in the case of primitive objects or types), pass as a parameter to other functions, etc., is said to be "first class".

Other languages, however, allow functions and other things else (like classes) are referenced and passed as argument. Example using JavaScript:

function teste() { alert("teste"); }
var x = teste;
x(); // Alerta "teste"

Support for first-class functions greatly simplifies the construction of certain functions. For example, if we want to sort a list, and we would like to specify a specific comparison criterion, we pass a function as a parameter to the sort method:

ordena([...], function(a,b) { /* compara A e B */ });

Instead of having to create a specific class to contain such function:

class MeuComparador implements Comparador {
    int comparar(Object a, Object b) { /* compara A e B */ }
}
ordena([...], new MeuComparador());

Lambda expressions go a step further, not only allowing functions to be passed as a parameter to other functions*, but also allowing them to be expressed as literals. A literal is a notation that represents a fixed value in the source code, that is, through the use of the syntax itself you can create an object that would otherwise require the combination of two or more different functionalities. Example (regular expressions in JavaScript):

var regex = /.../;             // Literal (o resultado já é um objeto RegExp)
var regex = new RegExp("..."); // Não literal (usa-se uma string, uma classe e o
                               // comando "new" para se construir o objeto

In Java 8, the literal for a lambda expression consists of a list of arguments (zero or more) followed by the operator -> followed by an expression that must produce a value. Examples:

() -> 42              // Não recebe nada e sempre retorna "42"
x -> x*x              // Recebe algo e retorna seu quadrado
(x,y) -> x + y        // Recebe dois valores e retorna sua soma

To understand the internal details, how this impacts the rest of the program, how type discovery is done, etc., I suggest reading the official documentation (in English), since it is an even new functionality (at least in this language). How to the advantages, the main one is the conciseness - do more thing by writing less code. There is often no reason to require a function to always be accompanied by a class, and using these expressions avoids many unnecessary constructs.

* note: as pointed out by @dstori, the introduction of lambda expressions in Java did not make functions first-class, since these expressions are converted to anonymous classes by the compiler (i.e. it is not yet can directly reference a method in Java, only indirectly through the object that defines it).

 46
Author: mgibsonbr, 2014-01-09 17:20:41

Is an attempt (unsuccessful in my opnion) to insert a functional feature into the language. In practice it will prevent you from having to create anonymous classes from just one method, as this is what lambda expressions do. Adding Listeners, Runnables, Callables and the like will get less verbose.

Instead of:

new Thread(new Runnble() {
  public void run() {
    System.out.println("Running...");
  }
}).start();

We will have:

new Thread(() -> System.out.println("Running with lambda")).start();
 10
Author: dstori, 2016-03-22 19:44:00

I think this question has a very large scope, and no answer that can be given here will be better than the Official Documentation . But in short, lambdas are constructs that make it possible to pass a code as a parameter.

The benefit is that you don't need to create a formal framework to specify this code. In general, you would need to specify a class (anonymous or not) and a method, within which your code would be. So with lambdas, you have only the code, which can be executed by your API.

Instead of listing advantages, disadvantages and examples, I put again the link from the official documentation, which brings a lot of details.

 4
Author: jpkrohling, 2013-12-13 11:48:49

A small example of how Lambada works and its biggest advantage !

List<String> lista = Arrays.asList("Java", "Lambda", "Lambda Expression");

We have a simple string list and we want to sort it by the smallest size. And how would we do that in Java? Well we can create a class and implement the Comparator in it and pass it as a parameter in sort or to not create a class just for that, we can use an anonymous class, more or less like that...

Collections.sort(lista, new Comparator<String>(){
      public int compare(String valor1, String valor2){
            return valor1.length() - valor2.length();
      }
});

We create a list and we are using the collections sort by passing the list we want sort and a Comparator where we use an anonymous class with the implementation of compare, it receives two values and in the implementation is to know who is the smallest, simple.

Now using the concepts of Lambda Expression, we will make the same Code:

Collections.sort(lista, (v1, v2) -> v1.length() - v2.length());
 3
Author: Ilya Budu, 2020-09-24 08:21:34