Java 8 Lambda Expressions: A Walk Through the Basics

Posted on Posted in Java

Java continues to remain the most popular programming language to date. Most probably because Java is the glue that binds a lot of other tech together, which means Java is everywhere. In Java 8,  we heard about lambda expressions.

Now let’s have a walk through the basics of lambda and learn how to use lambda expressions to make your code more readable and maintainable.

 

What is a Lambda Expression?Java 8 Lambda Expression

A lambda expression is a concise way to express a method of a class in an expression. Lambda expressions in Java are instances of functional interfaces. A functional interface is an interface that contains exactly one abstract method. It often represents abstract concepts like functions, actions, or predicates.

We use lambda expressions to create anonymous methods. However, sometimes a lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

 

Why Lambda?

  • Enables functional programming
  • Readable and concise code
  • Easier-to-user APIs and libraries
  • Enables support for parallel programming

Java 8 introduces new Collections stream API which utilizes the lambda expression and enables more functional programming approach. Stream API provides functionalities such as filtering, counting, mapping, looping, getting subsets and more in a shorter and more readable way.

 

Sample Lambda Expression:

The Arrow Operator

(int n) -> { 

             return n*n

}

(n) -> n*n

() -> System.out.print(“Hello World”);

 

The left side specifies the parameters required by the expression, which could also be empty if no parameters are required.

The right side is the lambda body which specifies the actions of the lambda expression. It might be helpful to think about this operator as “becomes”. For example, “n becomes n*n”, or “n becomes n squared”.

 

Frequently Used Interfaces

Below is a list of commonly used Java 8 functional interfaces.

InterfaceDescription
Consumer <T>Represents an operation that accepts a single input argument and returns no result.
Predicate<T>Represents a predicate (boolean-valued function) of one argument.
Supplier<T>Represents a supplier of results.

 

That’s all for Java 8 lambda basics. Have fun playing around with lambda and start writing code using the functional programming paradigm.

 

References:

https://docs.oracle.com/javase/8/docs/technotes/guides/language/lambda_api_jdk8.html https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.