Java 8 Tutorial: Lambda Expression
Java 8 Tutorial: Lambda Expression
Java 8 Tutorial: Lambda Expression
This java 8 tutorial list down important java 8 features and links to detailed tutorials posted on
HowToDoInJava.
Java 8 was released in early 2014. In java 8, most talked about feature was lambda expressions.
It has many other important features as well such as default methods, stream API and new
date/time API. Let’s learn about these new features in java 8 with examples.
Table of Contents
Lambda Expression
Functional Interface
Default Methods
Streams
Date/Time API Changes
Lambda Expression
Lambda expressions are not unknown to many of us who have worked on advanced languages
like Scala. In programming, a Lambda expression (or function) is just an anonymous function,
i.e., a function with no name and without being bounded to an identifier. They are written exactly
in the place where it’s needed, typically as a parameter to some other function.
either
(parameters) -> expression
or
(parameters) -> { statements; }
or
() -> expression
(x, y) -> x + y //This function takes two parameters and return their sum.
Please note that based on type of x and y, method may be used in multiple places. Parameters can
match to int, or Integer or simply String also. Based on context, it will either add two integers or
concat two strings.
Functional Interface
Functional interfaces are also called Single Abstract Method interfaces (SAM Interfaces). As
name suggest, they permit exactly one abstract method inside them. Java 8 introduces an
annotation i.e. @FunctionalInterface which can be used for compiler level errors when the
interface you have annotated violates the contracts of Functional Interface.
@FunctionalInterface
public interface MyFirstFunctionalInterface {
public void firstWork();
}
Please note that a functional interface is valid even if the @FunctionalInterface annotation
would be omitted. It is only for informing the compiler to enforce single abstract method inside
interface.
Also, since default methods are not abstract you’re free to add default methods to your functional
interface as many as you like.
@FunctionalInterface
public interface MyFirstFunctionalInterface
{
public void firstWork();
@Override
public String toString(); //Overridden from Object class
@Override
public boolean equals(Object obj); //Overridden from Object class
}
Default Methods
Java 8 allows you to add non-abstract methods in interfaces. These methods must be declared
default methods. Default methods were introduces in java 8 to enable the functionality of lambda
expression.
Default methods enable you to add new functionality to the interfaces of your libraries and
ensure binary compatibility with code written for older versions of those interfaces.
Moveable interface defines a method move() and provided a default implementation as well. If
any class implements this interface then it need not to implement it’s own version of move()
method. It can directly call instance.move(). e.g.
Output: I am moving
If class willingly wants to customize the behavior of move() method then it can provide it’s own
custom implementation and override the method.
Streams
Another major change introduced Java 8 Streams API, which provides a mechanism for
processing a set of data in various ways that can include filtering, transformation, or any other
way that may be useful to an application.
Streams API in Java 8 supports a different type of iteration where you simply define the set of
items to be processed, the operation(s) to be performed on each item, and where the output of
those operations is to be stored.
An example of stream API. In this example, items is collection of String values and you want
to remove the entries that begin with some prefix text.
List<String> items;
String prefix;
List<String> filteredList = items.stream().filter(e ->
(!e.startsWith(prefix))).collect(Collectors.toList());
Here items.stream() indicates that we wish to have the data in the items collection processed
using the Streams API.
Dates
Date class has even become obsolete. The new classes intended to replace Date class are
LocalDate, LocalTime and LocalDateTime.
If you want to use the date functionality with zone information, then Lambda provide you extra 3
classes similar to above one i.e. OffsetDate, OffsetTime and OffsetDateTime. Timezone
offset can be represented in “+05:30” or “Europe/Paris” formats. This is done via using another
class i.e. ZoneId.
Duration class is a whole new concept brought first time in java language. It represents the time
difference between two time stamps.
Duration deals with small unit of time such as milliseconds, seconds, minutes and hour. They
are more suitable for interacting with application code. To interact with human, you need to get
bigger durations which are presented with Period class.