Java 8 Tutorial

Java 8 was released in early 2014. This tutorial list down important Java 8 features with examples such as lambda expressions, Java streams, functional interfaces, default methods and date-time API changes.

Table of Contents

1. Lambda Expressions
2. Functional Interface
3. Default Methods
4. Streams
5. Date/Time API Changes

1. Lambda Expressions

Lambda expressions are known to many of us who have worked on other popular programming languages like Scala. In Java programming language, a Lambda expression (or function) is just an anonymous function, i.e., a function with no name and without being bounded to an identifier.

Lambda expressions are written exactly in the place where it’s needed, typically as a parameter to some other function.

1.1. Syntax

Few basic syntax of lambda expressions are:

(parameters) -> expression

(parameters) -> { statements; }

() -> expression

A typical lambda expression example will be like this:

//This function takes two parameters and return their sum
(x, y) -> x + y  

Please note that based on the type of x and y, the 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 concatenate two strings.

1.2. Rules for writing lambda expressions

  1. A lambda expression can have zero, one or more parameters.
  2. The type of the parameters can be explicitly declared or it can be inferred from the context.
  3. Multiple parameters are enclosed in mandatory parentheses and separated by commas. Empty parentheses are used to represent an empty set of parameters.
  4. When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses.
  5. The body of the lambda expressions can contain zero, one, or more statements.
  6. If the body of lambda expression has a single statement, curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression. When there is more than one statement in the body then these must be enclosed in curly brackets.

Read More: Java 8 Lambda Expressions Tutorial

2. Functional Interfaces

Functional interfaces are also called Single Abstract Method interfaces (SAM Interfaces). As name suggest, a functional interface permits exactly one abstract method in it.

Java 8 introduces @FunctionalInterface annotation which can be used for giving compile-time errors it a functional interface violates the contracts.

2.1. Functional Interface Example

//Optional annotation
@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 we can add default methods to the functional interface as many as we need.

Another important point to remember is that if a functional interface overrides one of the public methods of java.lang.Object, that also does not count toward the interface’s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

For example, given below is a perfectly valid functional interface.

@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
}

Read More: Java 8 Functional Interface Tutorial

3. Default Methods

Java 8 allows us to add non-abstract methods in the 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 us to introduce new functionality to the interfaces of our libraries and ensure binary compatibility with code written for older versions of those interfaces.

Let’s understand with an example:

public interface Moveable {
    default void move(){
        System.out.println("I am moving");
    }
}

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.

public class Animal implements Moveable{
    public static void main(String[] args){
        Animal tiger = new Animal();
        tiger.move();
    }
}
 
Output: I am moving

If class willingly wants to customize the behavior of move() method then it can provide its own custom implementation and override the method.

Reda More: Java 8 Default Methods Tutorial

4. Java 8 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 we 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.

4.1. Stream API Example

In this example, items is collection of String values and we 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.

Read More: Java 8 Internal vs. External Iteration

5. Java 8 Date/Time API Changes

The new Date and Time APIs/classes (JSR-310), also called as ThreeTen, which have simply change the way we have been handling dates in java applications.

5.1. Date Classes

Date class has even become obsolete. The new classes intended to replace Date class are LocalDate, LocalTime and LocalDateTime.

  1. The LocalDate class represents a date. There is no representation of a time or time-zone.
  2. The LocalTime class represents a time. There is no representation of a date or time-zone.
  3. The LocalDateTime class represents a date-time. There is no representation of a time-zone.

If we want to use the date functionality with timezone information, then Lambda provide us 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.

LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.of(12, 20);
LocalDateTime localDateTime = LocalDateTime.now(); 
OffsetDateTime offsetDateTime = OffsetDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Europe/Paris"));

5.2. Timestamp and Duration Classes

For representing the specific timestamp ant any moment, the class needs to be used is Instant. The Instant class represents an instant in time to an accuracy of nanoseconds.

Operations on an Instant include comparison to another Instant and adding or subtracting a duration.

Instant instant = Instant.now();
Instant instant1 = instant.plus(Duration.ofMillis(5000));
Instant instant2 = instant.minus(Duration.ofMillis(5000));
Instant instant3 = instant.minusSeconds(10);

Duration class is a whole new concept brought first time in java language. It represents the time difference between two timestamps.

Duration duration = Duration.ofMillis(5000);
duration = Duration.ofSeconds(60);
duration = Duration.ofMinutes(10);

Duration deals with a small unit of time such as milliseconds, seconds, minutes, and hours. They are more suitable for interacting with application code.

To interact with human, we need to get bigger durations which are presented with Period class.

Period period = Period.ofDays(6);
period = Period.ofMonths(6);
period = Period.between(LocalDate.now(), LocalDate.now().plusDays(60));

Read More: Java 8 Date and Time API Changes

Drop me your questions on this Java 8 tutorial in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

17 thoughts on “Java 8 Tutorial”

  1. I installed Java 8 on my Windows 10 PC (JDK 14.0.1_64_bin.exe), and tried running a simple HelloWorld java program. It compiled but, in execution, is throwing a JNI error as below. Any tips?

    A JNI error has occurred, please check your installation and try again.
    Exception in thread “main” java.lang.UnsupportedClassVersionError: HelloWorld has been compiled by a more recent version of the JavaRuntime (class file version 50.0), this version of the JavaRuntime only recognizes class file version up to 52.0.

    I get the same error for any Java program.

  2. Hello buddy, I tried the example using java but when I try to instantiate then I get compile time error.
    Cannot instantiate the type Moveable

  3. Hi,
    Very much interested and useful posts. Special thanks to you. is there any video tutorial available on website? if yes, share those details please.

  4. Mono<List> mp =	webClient.get().uri(accountMgmtURI)
    		.retrieve()
    		.bodyToMono(Map.class)
    		.flatMap(trans -> {
    			List content= (List) trans.get("content");
    			System.out.println("content :: "+content);
    			return Mono.just(content);
    		});
    
    		System.out.println("content :: "+mp.toString());
    );
    String	sites = mp.toString();
    
    • can someone help me on this , new to spring reactive my api response is :

      {
      “version”: “1.0”,
      “content”: [
      “12345”,
      “67076”,
      “123462”,
      “604340”,
      “1331999”,
      “1332608”,
      “1785581”,
      ]
      }

      need the “content”(list of string) to “sites” (string pipe separated)

  5. Very nice tutorials for reading. Can you also provide a PDF of your whole java 8 tutorial, as it is much helpful to read in offline mode.

  6. Hi Lokesh need help, i have a method, that will return User Object.

    public User getUserById(Integer uid) {
    	return (User) userList.stream().filter(user -> user.getId().equals(uid));
    }

    But this code throwing java.util.stream.ReferencePipeline$2 cannot be cast to com.pi.user.User,

    how to return a object.

  7. I’m beginner and your blogs are inspiration and I learnt a lot from it and I also just started a blog for java beginners at Place4Java.

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.