HudaTutorials.com

Java 8 Features - Stream, Lambda, Optional

Last updated on

Java 8 Features

What's New in JDK 8

New Features in Java 8

Java 8 Features : Java Standard Edition 8 is a major feature release for Java software development platform. Java 8 release included several features for simplify Java programming.

Features Added In Java 8

What's New in Java 8 ?

  1. Functional Interfaces
  2. Default And Static Methods In Interfaces
  3. Lambda Expressions
  4. Method References
  5. Optional Class
  6. Collectors Class
  7. forEach Method in Iterable Interface
  8. Collection API Improvements
  9. Java Stream API
  10. Java Date Time API
  11. Concurrency API improvements
  12. Java IO improvements
  13. Nashorn JavaScript engine
  14. Base64 Encode Decode
  15. Parallel Array Sorting
  16. JDK 8 includes Java DB 10.10

Functional Interfaces

Java 8 added new annotation @FunctionalInterface it is usually for compiler level errors.

What is @FunctionalInterface ?

The @FunctionalInterface is an annotation. It is used to declare the interface is a functional interface.

What is Functional Interface ?

The functional interface is a special interface that contains only one abstract method. It can have any number of default and static methods.

If the functional interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count.

Functional interfaces are also called as Single Abstract Method Interfaces or SAM Interfaces.

Which Package Contains the @FunctionalInterface Annotation ?

The java.lang package contains @FunctionalInterface annotation.

Java 8 @FunctionalInterface Example

package java8features;

@FunctionalInterface
public interface MyFunctionalInterface
{
    
    public void myAbstractMethod();
    
    public default void myDefaultMethod()
    {
        System.out.println("Functional Interface Default Method");
    }
    
    public static void myStaticMethod()
    {
        System.out.println("Functional Interface Static Method");
    }
    
}

You can omit the annotation, @FunctionalInterface and your functional interface will still be a valid one. The use of @FunctionalInterface annotation is to inform the compiler that the interface will have a single abstract method.

The default methods are Non-abstract and you can add as many default methods in the functional interface as you like.

If an interface has an abstract method that overrides one of the public methods of java.lang.object then it is not considered as the interface's abstract method. Following functional interface is valid interface by definition.

package java8features;

@FunctionalInterface
public interface MyFunctionalInterface
{
    
    public void myAbstractMethod();
    
    @Override
    public String toString(); //Overridden from Object class
 
    @Override
    public boolean equals(Object obj); //Overridden from Object class
    
}

Default And Static Methods In Interfaces

Java 8 allows default and static methods in interfaces.

package java8features;

public interface MyInterface
{
    
    public void myAbstractMethod();
    
    public String mySecondAbstractMethod();
    
    public default void myDefaultMethod()
    {
        System.out.println("Default Method in Interface");
    }
    
    public static void myStaticMethod()
    {
        System.out.println("Static Method in Interface");
    }
    
}

Lambda Expressions

Java 8 introduces a new feature lambda expressions.

What is Lambda Expression ?

A function with no name and an identifier. In other words a Lambda Expression (or function) can be defined as an anonymous function.

Lambda expressions are defined exactly in the place where they are needed, usually as a parameter to some other function.

Following are the Lambda Expression Syntax :

  1. ( Parameters ) -> Expression
  2. ( Parameters ) -> {Expression 1; Expression 2; Expression n;}
  3. ( ) -> Expression

Lambda Expression Examples for above syntaxes

  • (x, y) -> x + y
  • (x, y) -> {int z = (x + y}; int k = (z + 10); ++k;}
  • ( ) -> 10 + 20

Method References

The Method reference feature is a shorthand notation for Lambda Expressions to call a method of Functional Interface. Replace Lambda Expression with method reference.

interface MyInterface 
{
	void display();
}

class MyDerivedClass
{
	public void derivedClassMethod()
	{
		System.out.println("Derived Class Method");
	}
}

public class MethodReference
{
	public static void main(String args[])
	{
		MyDerivedClass mdc = new MyDerivedClass();
		MyInterface  mi = mdc::derivedClassMethod; 
		mi.display();
	}
}

How Many Types of Method References in Java 8 ?

There are 3 types of method references in Java.

  • Reference to Constructor
  • Reference to Static method
  • Reference to an Instance Method

Optional Class

Optional class is introduced in Java 8. It exists in java.util package. Optional class provides methods that are used to check the presence of value for a particular variable.

import java.util.Optional;
public class OptionalClassExample
{
	public static void main(String args[])
	{
		String str = null;
		Optional<String> checkNull = Optional.ofNullable(str);
		if (checkNull.isPresent())
		{
			System.out.print(str);
		}
		else
		{
			System.out.println("String is Null");
		}
	}
}

Collectors Class

Collectors class provides various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria.

forEach Method in Iterable Interface

The java.lang.Iterable interface added a new method called forEach in Java 8. The forEach method can iterate over the elements in the collection. It is a default method defined in the Iterable interface.

The forEach method takes the functional interface as a single parameter. You can pass Lambda Expression as an argument.

forEach Method in Iterable Interface Example

import java.util.List;
import java.util.ArrayList;

public class ForEachMethodExample
{
	public static void main(String args[])
	{

		List<String> subjects = new ArrayList<>();
		subjects.add("Java");
		subjects.add(".Net");
		subjects.add("Python");
		subjects.add("Spring Boot");
		
		subjects.forEach(subject -> System.out.println(subject));
	}
}

Collection API Improvements

  1. forEachRemaining Method of Iterator : Performs the given action for each remaining element until all elements have been processed or the action throws an exception.
  2. removeIf Method of Collection : Removes all of the elements of this collection that satisfy the given predicate.
  3. spliterator Method of Collection : Returns Spliterator instance which you can use for traversing the elements in either sequential or parallel fashion.
  4. Map collection has replaceAll (), compute() and merge() methods.
  5. HashMap class with Key collisions has been improved to enhance performance.

Java Stream API

Java 8 provides a new package java.util.stream. The stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods those are pipelined to produce the desired result.

Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines. A stream pipeline consists of a source such as a Collection, an array, a generator function, or an I/O channel followed by zero or more intermediate operations such as Stream.filter or Stream.map and a terminal operation such as Stream.forEach or Stream.reduce.

Java Date Time API

JDK 8 introduced new Date/Time API as java.time package. The java.time API is consistent domain models for date, time, duration and periods.