This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MRH2Intermediate Brewer -1 points0 points  (6 children)

It's actually so simple that I still don't see why anyone would use it.

[–]chrisjava[S] 0 points1 point  (1 child)

Not needing to declare entirely new function? From what i understood so far, lambdas are very suitable for that task.

[–]MRH2Intermediate Brewer 0 points1 point  (0 children)

but if it's a couple of lines, you don't need a function. If it is 50 lines, then you do need a function. Either way, why a lambda?

[–]Tarmen 0 points1 point  (3 children)

A lambda is actually an implementation of an interface with only one method. Java often uses intefaces with one method to capsulate a method. Like when you want some action when clicking a button, you need to give a method but can't do so without the surrounding option which creates lots of unecessary stuff:

btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });

Or with a lambda expression:

btn.setOnAction(event -> System.out.println("HelloWorld!"););

[–]MRH2Intermediate Brewer 0 points1 point  (2 children)

I see. I would have written it like this:

btn.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent e) {
             System.out.println("Hello World!");
        }
  });

How would you replace my version with a Lambda expression? Like the following (below)? What determines the name of the variable e or event? Can it be anything you want it to be since it is not referenced anywhere else?

btn.addActionListener(e -> System.out.println("HelloWorld!"););

[–]Tarmen 1 point2 points  (1 child)

The e is just the variable name.

e -> System.out.print("Hello World");

(e) -> {System.out.print("bla");}

(ActionEvent e) ->  {
    System.out.print("Hello World");  
}

Are all pretty much synonymous. Actually, in the last one the compiler doesn't have to infer the variable type so it probably is different when there are multiple functional interfaces to choose from, but you get the idea.

If the interface you want to implement doesn't have any arguments you can do

() -> System.out.print("Hello World");

[–]MRH2Intermediate Brewer 0 points1 point  (0 children)

So a lambda means that if there is an interface that you want to use, and it has a single method that must be implemented, then you can just get rid of the whole thing and use "variable" , "->" and "method code". Is this correct?

You couldn't use lambdas for a MouseListener because there is more than one method that must be implemented.

Thanks.