RE: [Programming][Java][Guide] Using Lambda Expressions In Java [Part 1]

You are viewing a single comment's thread from:

[Programming][Java][Guide] Using Lambda Expressions In Java [Part 1]

in programming •  7 years ago  (edited)

Can I use the lambda everytime I would pass an object that implements an interface?
Like the example below:

JButton button = new JButton();
// Without Lambda
button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Doing something.");
    }
});
// With Lambda
button.addActionListener(e -> {
    System.out.println("Doing something.");
});
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Yes, due to the JButton#addActionListener() method expecting a ActionListener type object. Because this method is expecting an ActionListener, and the type has one implementable method actionPerformed(ActionEvent e), we can substitute it with a lambda expression which as we can see needs a parameter value for ActionEvent, so we reference it using the name you chose e, though can be anything the writer chooses (though note it should always be lowerCamelCase format as it fits into Java Conventions. But a single lowercase letter is usually easiest IMO).

This also applies to methods that have more than a single parameter as well!

I hope I didn't make that sound to confusing.

Thanks for the answer, that helped me a lot. =)