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

in #programming7 years ago (edited)

My first post on Steemit, and I hope it's good!

This is will be a start of a series (depending on how many people are interested) on Java development. I have been programming for over 8 years, and one language I have used almost every day since I started has been Java. I hope to show people the information I wish I had when I started. The first entries in this series will be geared towards beginners, though I hope to include more advanced topics such as deobfuscation, refactoring, injection, and much more down the road.

Lambdas Part I

Alright, though I won't be going into every detail about what Lambdas are; I will be showing everyone how useful lambdas are, and how they make the writer's life easier.

Behold... The holy:

(The mathematical symbol for lambda)

Technically speaking, MSDN defines lambdas in computer science as:

"A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls."

Don't worry if that made no sense. After a few examples, they won't seem so daunting!

A simple example of a usage of lambda would be using it with Java's 8 introduction of the foreach function:

List<String> names = new ArrayList<>();
Collections.addAll(names, "Peter", "Bob", "Sally", "Ashley", "Jim"); 
names.foreach(name -> System.out.println(name));

Did you notice the lambda expression?
If you didn't. The actual lambda expression used was:
name -> System.out.println(name)

Let's break this down, to help get a better understanding:
'name': the current value of the foreach
'->': our lambda expression operator
System.out.println(name): our call to Java's print method, outputing our current foreach value

Well this just looks more complicated than a normal for-loop! What makes this better?

Two words. Less typing. This can help increase a writers workflow, and let us be honest, no one wants to type more than they really need to right?

Let's compare the differences of the same methods, without using lambda expressions so that we can see the differences!

Indexed For-Loop:

List<String> names = new ArrayList<>();
Collections.addAll(names, "Peter", "Bob", "Sally", "Ashley", "Jim"); 
for(int i = 0; i < names.size(); i++) {
    String name = names.get(i);
    System.out.println(name);
}

Java 7 and Prior For-Each:

List<String> names = new ArrayList<>();
Collections.addAll(names, "Peter", "Bob", "Sally", "Ashley", "Jim"); 
for(String name : names) {
    System.out.println(name);
}

Now remind you that all these lines of code are identical in terms of logic, just their implementation varies! By observing each one, we can now clearly see the lambda expression we wrote earlier has fewer lines, which is our goal! Less work on the writer!

Are there any other applicable uses for lambdas throughout Java?
Of course! Too many to count! Let's go through a few more to help you understand better! Below, we see how we could create an object with implementable methods.

In Java 7 and prior, when creating an object, a Runnable in this case, which has an implementable method you would need to extend it by typing the whole function, as so:

Runnable s = new Runnable() {
    public void run() {
        //I'm inside the run method.
    }
};

Yet with the introduction of lambda's in Java 8, we can now do the same with only typing:

Runnable s = () -> {
    //I'm inside the run method.
};

You may be asking yourself, how is this possible?
Without getting too technical; when creating a Runnable reference, it is expecting a certain type (a.k.a. Runnable), therefore using lambdas we can pass a generic type, that will fulfill the same requirements needed by the type. Please note, this does not apply to everything; some types are too complex to be represented by lamdas!

Part II Coming Soon...
I hope you enjoyed reading the first part of this guide! Part two will contain more lambda examples and the introduction of method references, and will be published in the next few days!
Please if you find anything wrong with my guide, have questions, or just suggestions for future guides feel free to comment below! Also, upvote if you can! :D

Thank you!

Sort:  

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.");
});

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

Congratulations @notoriouspp! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

SteemitBoard Ranking update - A better rich list comparator
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @notoriouspp! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.17
TRX 0.15
JST 0.029
BTC 56790.06
ETH 2345.62
USDT 1.00
SBD 2.42