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


Java 8 will be released soon ( March 2014 ) and the feature of this version are Lambda expressions .

Could anyone describe, as the question says, what this feature will actually add to the developers and, if possible, any example code commented on?

asked by anonymous 13.12.2013 / 12:29

4 answers


Lambda expressions are a common feature in many languages, particularly those that follow the Functional Programming (the term itself comes from the Lambda Calculus , mathematical foundation that underpins this paradigm), but which have recently been introduced into languages of other paradigms (such as the Imperative / Object Oriented). To understand them, you need to know the concepts of first-class functions and literals .

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

Other languages, however, allow functions and other things (such as classes) to be referenced and passed as arguments. Example using JavaScript:

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

Supporting first-class functions greatly simplifies the construction of certain functions. For example, if we want to sort a list, and 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 hold such a function:

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

Lambda expressions go one step further, not only allowing you to pass functions 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 should 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 , because it is a new feature (at least in this language). As for the advantages, the main one is conciseness - doing more writing less code. Often there is no reason to require that a function be always accompanied by a class, and the use of such expressions avoids many unnecessary constructions.

* Note: As pointed out by @dstori, the introduction of lambda expressions in Java did not make the first-class functions, since these expressions are converted to anonymous classes by the compiler (that is, it is not yet possible to direct reference to a Java method, only indirect through the object that defines it).

13.12.2013 / 13:21

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

Instead of:

new Thread(new Runnble() {
  public void run() {

We will have:

new Thread(() -> System.out.println("Running with lambda")).start();
13.12.2013 / 12:46

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 briefly, lambdas are constructs that make it possible to pass code as a parameter.

The benefit is that you do not need to create a formal structure 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, re-insert the link from official documentation , which brings many details.

13.12.2013 / 12:48

A small example of how Lambada works and the biggest advantage of it!

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

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

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 sort of Collections passing the list that we want to 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 smaller, / p>

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

Collections.sort(lista, (v1, v2) -> v1.length() - v2.length());
15.10.2018 / 16:13