Java 8

Java 8 - 2014 ( Spider )

1. Describe the newly added features in Java 8?

Here are the newly added features of Java 8:

Feature Name Description
Lambda expression A function that can be shared or referred to as an object.
Functional Interfaces Single abstract method interface.
Method References Uses function as a parameter to invoke a method.
Default method It provides an implementation of methods within interfaces enabling 'Interface evolution' facilities.
forEach() Method In Iterable Interface Java.lang interface now supports a “forEach” function. Iterable that can iterate over the collection’s items. The Iterable interface has a default method called “forEach.”
Stream API Abstract layer that provides pipeline processing of the data.
Date Time API New improved joda-time inspired APIs to overcome the drawbacks in previous versions
Optional Wrapper class to check the null values and helps in further processing based on the value.
Nashorn, JavaScript Engine An improvised version of JavaScript Engine that enables JavaScript executions in Java, to replace Rhino.

Functional interfaces

Functional Interfaces are an interface with only one abstract method (Single Abstract Method (SAM)).
functional -> wraps a function as an interface.

default method

static method

Static methods, which contains method implementation is owned by the interface and is invoked using the name of the interface, it is suitable for defining the utility methods and cannot be overridden.

Example of pre-defined functional interfaces

java.util.function

Some of the famous pre-defined functional interfaces from previous Java versions are Runnable, Callable, Comparator, and Comparable. While Java 8 introduces functional interfaces like Supplier, Consumer, Predicate, etc. Please refer to the java.util.function doc for other predefined functional interfaces and its description introduced in Java 8.

Runnable: use to execute the instances of a class over another thread with no arguments and no return value ( run() ). 

Callable: use to execute the instances of a class over another thread with no arguments and it either returns a value or throws an exception.

Comparator: use to sort different objects in a user-defined order

Comparable: use to sort objects in the natural sort order

Categories of pre-defined function interfaces (new in Java 8)

Function: To transform arguments in returnable value.

Predicate: To perform a test and return a Boolean value.

Consumer: Accept arguments but do not return any values.

Supplier: Do not accept any arguments but return a value. 

Operator: Perform a reduction type operation that accepts the same input types.

Lambda expression

FunctionalInterface fi = (String name) -> { 
System.out.println("Hello "+name); 
return "Hello "+name; 
}

Predicate<String> stringPredicate = s -> s.isEmpty(); 
Predicate<List> listPredicate = s -> s.isEmpty();
Function<String, Boolean> func = s -> s.isEmpty();
Consumer<String> stringConsumer = s -> s.isEmpty();

Common ways to use the expression

Assignment to a functional Interface —> Predicate<String> stringPredicate = s -> s.isEmpty();
Can be passed as a parameter that has a functional type —> stream.filter(s -> s.isEmpty())
Returning it from a function —> return s -> s.isEmpty()
Casting it to a functional type —> (Predicate<String>) s -> s.isEmpty()

Method Reference

class::methodName

Integer::parseInt(str) \\ method reference

str -> Integer.ParseInt(str); \\ equivalent lambda

Means that we could create object of Functional interface by simply passing method (static or instance or constructor) of existing class.

Sayable sayable = MethodReference::saySomething;  

forEach

It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach() method to iterate elements.

This method takes a single parameter which is a functional interface. So, you can pass lambda expression as an argument.

    public static void main(String[] args) {  
        List gamesList = new ArrayList();  
        gamesList.add("Football");  
        gamesList.add("Cricket");  
        gamesList.add("Chess");  
        gamesList.add("Hocky");  
        System.out.println("------------Iterating by passing lambda expression--------------");  
        gamesList.forEach(games -> System.out.println(games));  
		
        System.out.println("------------Iterating by passing method reference---------------");  
        gamesList.forEach(System.out::println);  

		// forEachOrdered() - iterating using stream		
        System.out.println("------------Iterating by passing lambda expression---------------");  
        gamesList.stream().forEachOrdered(games -> System.out.println(games));  
        System.out.println("------------Iterating by passing method reference---------------");  
        gamesList.stream().forEachOrdered(System.out::println);  		
          
    } 

Stream API

A new java.util.stream has been added in Java 8 to perform filter/map/reduce like operations with the collection. Stream API will allow sequential as well as parallel execution.

Collection interface has been extended with stream() and parallelStream() default methods t

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class StreamExample {

	public static void main(String[] args) {
		
		List<Integer> myList = new ArrayList<>();
		for(int i=0; i<100; i++) myList.add(i);
		
		//sequential stream
		Stream<Integer> sequentialStream = myList.stream();
		
		//parallel stream
		Stream<Integer> parallelStream = myList.parallelStream();
		
		//using lambda with Stream API, filter example
		Stream<Integer> highNums = parallelStream.filter(p -> p > 90);
		//using lambda in forEach
		highNums.forEach(p -> System.out.println("High Nums parallel="+p));
		
		Stream<Integer> highNumsSeq = sequentialStream.filter(p -> p > 90);
		highNumsSeq.forEach(p -> System.out.println("High Nums sequential="+p));

	}

}
More information Core 8 Streams

Optional

In Java 8, the “java.util” package included an optional class. The public final class “Optional” is used to handle NullPointerException in a Java program.

Examples