Hi all..I brought you an article based on a topic which is not a well known one for everyone who knows Java. It's Lambda Expressions! Do you know about them? Actually, it was introduced in Java SE 8 as a further enhancement to the Anonymous Inner Classes in Java.

So what are Anonymous Inner Classes?  A class with no name is called as anonymous inner class. You can see an example below. Java threads provides this implementation.


public class LambdaDemo {

    public static void main(String[] args) {

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                System.out.println("Thread created");
            }
        }).start();

    }
}

We are implementing the methods on the go, when we needed and without a class name. Otherwise we can not create instances from interfaces in Java! When I'm going to do this several interfaces, it's obvious that code becomes messy.. So, Java introduced some kind of enhancement to this using  lambda expressions.

Lambda Expressions are based on Functional Interfaces. The interfaces which contains only one method(abstract method) is considered as a functional interface. So, whenever we use a interface with one and only method, we can use lambda expressions wherever that interface is used in the code.

Java uses an annotation in the internal implementations, to ensure that the required interfaces are declared as functional interfaces. That annotation is called as @FunctionalInterface. You can go into the Runnable interface in Java and see this annotation. It will be displayed like this.

@FunctionalInterface
public interface Runnable {
    void run();
}
Like this, Java has another Functional Interface called Predicate with test method used in Java streams filter method.
Another instance for functional interfaces is Consumer interface with accept method used in Java collections forEach method.

The basic format of declaring a lambda expressions is given below.

(arguments) -> { body } OR
() -> body


Advantages of Lamba :

1. Enable considering functionality as a method argument (we will see later)
2. It can be used with implementation easily whenever we want
3. Reduce lines of code

Let's see how we can use lambda expressions...

Java collections method called as forEach to loop though the elements. Let's use this method with Lambda. It takes a consumer method as as the argument.

List<String> names = Arrays.asList("Sam", "Bob", "Sim");
names.forEach(number -> System.out.print(number + " "));

Java streams filter method also takes a Predicate as the argument.

Predicate<String> predicate = name -> name.startsWith("S");
List<String> namesWithLetter = names.stream()
.filter(predicate)
.collect(Collectors.toList());
System.out.println(namesWithLetter);

Java threads run method can be also overridden using a lamba.

Runnable runnable = () -> System.out.println(Thread.currentThread().getName());
Thread thread = new Thread(runnable);
thread.start();

Find the Java snippet below where I have used all the above methods.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class LambdaDemo {
public static void main(String[] args) {
// CREATE SEPARATE CONSUMER TO MAKE STRINGS UPPERCASE
List<String> names = Arrays.asList("Sam", "Bob", "Sim");
// APPLY LAMBDA
names.forEach(number -> System.out.print(number + " "));
// APPLY LAMBDA WITH METHOD REFERENCE
names.forEach(System.out::println);
// CONSUMER "ACCEPT" METHOD IMPLEMENTATION
Consumer<String> changeCase = a -> System.out.println(a.toUpperCase());
// PASS LAMBDA AS A METHOD ARGUMENT
names.forEach(changeCase);
// PREDICATE "TEST" METHOD IMPLEMENTATION
Predicate<String> predicate = name -> name.startsWith("S");
// PROCESS DATA WITH FILTER
List<String> namesWithLetter = names.stream().filter(predicate).collect(Collectors.toList());
// PASS LAMBDA AS A METHOD ARGUMENT
System.out.println(namesWithLetter);
// RUNNABLE "RUN" METHOD IMPLEMENTATION
Runnable runnable = () -> System.out.println(Thread.currentThread().getName());
// PASS LAMBDA AS A OBJECT TO THE CONSTRUCTOR
Thread thread = new Thread(runnable);
thread.start();
}
}
view raw LambdaDemo.java hosted with ❤ by GitHub

Now we have reached to the end of this article guys! The knowledge I have on Lambda Expressions was included here as much as I can. So try to read carefully and grab the concepts..

I will be back with another article on Java later.. Till then,

Good Bye everyone!






30 Comments

  1. Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man,Keep it up. Meanwhile visit our website for IMT ASSIGNMENT

    ReplyDelete
  2. Nice informative post on how java expressions works

    ReplyDelete
  3. leasant to be going by your web journal once more, it has been months for me. Well this article i've been sat tight for so long.digital marketing coruse I require this article to finish my task in the school, and it has same theme with your articledigital marketing coruse

    ReplyDelete
  4. Nice informative post on how java expressions works
    mobiledokan

    ReplyDelete
  5. Nice informative post on how java expressions works ktm bike price

    ReplyDelete
  6. The process must also be respectful of intellectual property.

    ReplyDelete
  7. ice informative post on how java expressions works Digital marketing

    ReplyDelete
  8. atly affects the new innovation. A debt of gratitude is in order for sharing itBd IT

    ReplyDelete
  9. A class with no name is called as anonymous inner class. You can see an example below. mobile price usa

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. The sites accessed through Tor come in all shapes dark web links and sizes, and some are downright strange. For example, there's a site that hosts downloadable comic books that you can read offline. Then there's a website that provides information on black-hat hacking, which isn't legal in most countries. And you can find sites that discuss conspiracy
    theories and other spooky topics on the dark web, too.

    ReplyDelete
  12. Get top-notch Law assignment help from qualified experts. We offer personalized support to enhance your understanding and improve your grades in legal coursework.

    ReplyDelete
  13. 11Xplay is your go-to platform for an unparalleled online gaming experience, offering sports betting and casino games designed specifically for Indian players. Enjoy live sports betting, favorite games such as Teen Patti and Rummy, along with fast, secure payments and instant withdrawals. The platform boasts a user-friendly interface and 24/7 customer support to ensure a hassle-free experience. Explore other top-notch platforms like Lotusbhai and Betbook250 to elevate your gaming journey to the next level!

    ReplyDelete
  14. Welcome to 1xbet – your trusted gateway to 1xBet’s world of gaming and entertainment. We provide a seamless, secure login experience for users to access live sports, casino games, and global events with ease.

    ReplyDelete
  15. T10 Exchange offers seamless online gaming and sports exchange experiences. With a user-friendly interface, diverse game options, secure transactions, and 24/7 customer support, it’s the go-to platform for enthusiasts. Explore innovative features and join a trusted community to enhance your gaming journey.

    ReplyDelete
  16. Satsport is your ultimate destination for cutting-edge sports insights and services in India. Offering a seamless platform for sports enthusiasts, we specialize in delivering real-time updates, secure transactions, and an unmatched user experience. Discover the best of sports engagement with Satsports today!"

    ReplyDelete
  17. your ultimate destination for cutting-edge sports insights and services in India. Offering a seamless platform for sports enthusiasts, we specialize in delivering real-time updates, secure transactions, and an unmatched user experience. Discover the best of sports engagement with Satsports today!"Pinterest Marketing

    ReplyDelete
  18. This is fantastic! I want to write like this, but procrastination often seems to hold me back. Thanks for sharing! Walmart Automation services

    ReplyDelete
  19. Incredible! I wish I could create something like this, but procrastination often holds me back. Thanks for sharing the encouragement! what challenges did amazon face in the beginning

    ReplyDelete
  20. Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man,Keep it up. Meanwhile visit our website for mourin seo expert .

    ReplyDelete
  21. Digital marketing is the practice of promoting products, services, or brands using online channels digital marketer such as search engines, social media, email, and websites. It includes strategies like SEO, content marketing, pay-per-click (PPC) advertising, social media marketing, and email campaigns to engage target audiences

    ReplyDelete
  22. Java uses an annotation in the internal implementations, to ensure that the required interfaces are declared as functional interfaces

    ReplyDelete
  23. I have to say, this article left a lasting impression on me. News hub The way you presented the information was both empathetic and thorough, which is not always easy to do with such sensitive topics.

    ReplyDelete