What are the advantages of Lambda Expressions in Java 8?

Asked

Viewed 12,597 times

52

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

One could describe, as the question says, what this feature will add in practice to developers and, if possible, some example of commented code?

  • I arrived late, unfortunately already closed your question. My suggestion is simply that you take some cool project to do and start experimenting. You can learn fast and you will see that the code is much better with Amblas. He is something even Generics was 8 years ago: At first, everyone thought it was too complicated, too tricky and unnecessary, but over time the people began to realize that it was actually a very important thing that you couldn’t understand because it wasn’t in java from the beginning.

  • Placed a question in the goal concerning this question.

  • 3

    I voted to reopen, as for the adoption of lambda had to be justified by the JCP rules in JSR-335, and these justifications can be presented objectively as an answer here.

4 answers

46


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

Traditionally in Java, a method (function, procedure) exists only as a member of a class. This means that although you may have a variable "pointing" to an object, you cannot store a method in a variable. All that is allowed to reference in a language (in the case primitive objects or types), to pass as 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"

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 a 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 you to pass functions as parameters 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 the discovery of types is made, etc, I suggest reading the official documentation (in English), because it is still a new feature (at least in this language). As for the advantages, the main one is the concision - do more by writing less code. There is often no reason to require a function to be always accompanied by a class, and the use of these expressions avoids many unnecessary constructs.

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

11

It is an attempt (unsuccessful in my opinion) to insert a functional feature in 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. Addition of Listeners, Runnables, Callables and the like will become 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();
  • 7

    Heheh, "unsuccessful" already? Maybe it could be better, but give a little time for the parade to try to succeed. It is visible the improvement in this example you gave. =)

  • 1

    I agree with the improvement in "this specific scenario" Aelia, but in many other cases it was due. What’s more, in a structure that is yours (different from runnables, listeners and the like) you will have to create a functional interface (urghhh) to use lambda (urghh again).

  • "will prevent you from having to create anonymous classes from just one method, as this is what lambda expressions do" Well noted! For a moment I thought that finally Java would support first class functions, but I see that this is not the case...

  • 2

    I am working on a project that uses Amblas, and in my opinion are very successful.

  • I don’t think it will be unsuccessful, I believe it will improve enough!

5

I think that this question has a very large scope, and no answer that can be given here will be better than the official documentation. But in a nutshell, Lambdas are constructions that make it possible to pass a code as a parameter.

The benefit is that you don’t 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. Then, with both, you have only the code, which can be run by your API.

Instead of listing advantages, disadvantages and examples, I put the official documentation link, that brings many details.

4

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 that in Java? Well we can create a class and implement Comparator and pass it as a parameter in Sort or not to create a class just for that, we can use an anonymous class, more or less like this...

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

We created a list and we are using the Collections Sort by passing the list we want to sort and a Comparator where we use an anonymous class with the compare implementation, it receives two values and in the implementation is knowing 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());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.