You are viewing a single comment's thread from:

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

in #programming7 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.");
});
Sort:  

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. =)

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.029
BTC 56618.92
ETH 2337.15
USDT 1.00
SBD 2.40