java 8 lambda built-in functional interfaces

32
JAVA 8: LAMBDA BUILT-IN FUNCTIONAL INTERFACES ganesh samarthyam [email protected]

Upload: ganesh-samarthyam

Post on 08-Jan-2017

614 views

Category:

Software


4 download

TRANSCRIPT

JAVA 8: LAMBDA BUILT-IN FUNCTIONAL INTERFACES

ganesh samarthyam [email protected]

Functional interfaces

@FunctionalInterface interface LambdaFunction { void call(); }

Functional interface

Abstract method providing the signature of the lambda function

Annotation to explicitly state that it is a functional interface

Java 8 lambdas - “Hello world!”

@FunctionalInterface interface LambdaFunction { void call(); }

class FirstLambda { public static void main(String []args) { LambdaFunction lambdaFunction = () -> System.out.println("Hello world"); lambdaFunction.call(); } }

Functional interface - provides signature for lambda functions

Lambda function/expression

Call to the lambda

Prints “Hello world” on the console when executed

Older Single Abstract Methods (SAMs)

// in java.lang package interface Runnable { void run(); }

// in java.util package interface Comparator<T> { boolean compare(T x, T y); }

// java.awt.event package: interface ActionListener { void actionPerformed(ActionEvent e) }

// java.io package interface FileFilter { boolean accept(File pathName); }

Functional interfaces: Single abstract methods

@FunctionalInterface interface LambdaFunction { void call();

// Single Abstract Method (SAM) }

Using built-in functional interfaces// within Iterable interface default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t);

} }

// in java.util.function package @FunctionalInterface public interface Consumer<T> {

void accept(T t); // the default andThen method elided

}

Using built-in functional interfaces

List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString);

List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string));

Built-in functional interfaces

Built-in functional interfaces are a part of the java.util.function

package (in Java 8)

Built-in interfacesPredicate<T> Checks a condition and returns a

boolean value as resultIn filter() method in java.util.stream.Stream which is used to remove elements in the stream that don’t match the given condition (i.e., predicate) as Consumer<T> Operation that takes an argument but

returns nothingIn forEach() method in collections and in java.util.stream.Stream; this method is used for traversing all the elements in the collection or Function<T,

R>Functions that take an argument and return a result

In map() method in java.util.stream.Stream to transform or operate on the passed value and return a result.

Supplier<T> Operation that returns a value to the caller (the returned value could be same or different values)

In generate() method in java.util.stream.Stream to create a infinite stream of elements.

Predicate interface

Stream.of("hello", "world") .filter(str -> str.startsWith("h")) .forEach(System.out::println);

The filter() method takes a Predicate as an argument (predicates are

functions that check a condition and return a boolean value)

Predicate interface

Predicate interface

A Predicate<T> “affirms” something as true or false: it takes an argument of type T, and returns a

boolean value. You can call test() method on a Predicate object.

@FunctionalInterface public interface Predicate<T> {

boolean test(T t); // other methods elided

}

Predicate interface: Example

import java.util.function.Predicate;

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

Predicate<String> nullCheck = arg -> arg != null; Predicate<String> emptyCheck = arg -> arg.length() > 0; Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck); String helloStr = "hello"; System.out.println(nullAndEmptyCheck.test(helloStr)); String nullStr = null; System.out.println(nullAndEmptyCheck.test(nullStr));

} }

Prints: truefalse

Predicate interface: Example

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

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

List<String> greeting = new ArrayList<>(); greeting.add("hello"); greeting.add("world"); greeting.removeIf(str -> !str.startsWith("h")); greeting.forEach(System.out::println);

} }

Prints: hello

Consumer interface

Stream.of("hello", "world") .forEach(System.out::println);

// void forEach(Consumer<? super T> action);

Prints: helloworld

Consumer interface

Consumer interface

A Consumer<T> “consumes” something: it takes an argument (of generic type T) and returns

nothing (void). You can call accept() method on a Consumer object.

@FunctionalInterface public interface Consumer<T> {

void accept(T t); // the default andThen method elided

}

Consumer interface: Example

Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase());

printUpperCase.accept("hello");

Prints: HELLO

Consumer interface: Example

import java.util.stream.Stream; import java.util.function.Consumer;

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

Stream<String> strings = Stream.of("hello", "world"); Consumer<String> printString = System.out::println; strings.forEach(printString);

} }

Prints: helloworld

Function interface

import java.util.Arrays;

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

Arrays.stream("4, -9, 16".split(", ")) .map(Integer::parseInt) .map(i -> (i < 0) ? -i : i) .forEach(System.out::println);

} }

Prints: 4916

Function interface

Function interface

A Function<T, R> “operates” on something and returns something: it takes one argument (of

generic type T) and returns an object (of generic type R). You can call apply() method on a Function

object.

@FunctionalInterface public interface Function<T, R> {

R apply(T t); // other methods elided

}

Function interface: Example

Function<String, Integer> strLength = str -> str.length(); System.out.println(strLength.apply("supercalifragilisticexpialidocious"));

Prints: 34

Function interface: Example

import java.util.Arrays; import java.util.function.Function;

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

Function<String, Integer> parseInt = Integer:: parseInt ; Function<Integer, Integer> absInt = Math:: abs ; Function<String, Integer> parseAndAbsInt = parseInt.andThen(absInt); Arrays.stream("4, -9, 16".split(", "))

.map(parseAndAbsInt)

.forEach(System. out ::println); }

}

Prints: 4916

Supplier interface

import java.util.stream.Stream; import java.util.Random;

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

Random random = new Random(); Stream.generate(random::nextBoolean)

.limit(2)

.forEach(System.out::println); }

}

Prints two boolean values “true” and “false”

in random order

Supplier interface

Supplier interface

A Supplier<T> “supplies” takes nothing but returns something: it has no arguments and

returns an object (of generic type T). You can call get() method on a Supplier object

@FunctionalInterface public interface Supplier<T> {

T get(); // no other methods in this interface

}

Supplier interface: Example

Supplier<String> currentDateTime = () -> LocalDateTime.now().toString(); System.out.println(currentDateTime.get());

Prints current time: 2015-10-16T12:40:55.164

Summary of built-in interfaces in java.util.function interface

❖ There are only four core functional interfaces in this package: Predicate, Consumer, Function, and Supplier.

❖ The rest of the interfaces are primitive versions, binary versions, and derived interfaces such as UnaryOperator interface.

❖ These interfaces differ mainly on the signature of the abstract methods they declare.

❖ You need to choose the suitable functional interface based on the context and your need.

Check out our book!

❖ “Oracle Certified Professional Java SE 8 Programmer Exam 1Z0-809”, S.G. Ganesh, Hari Kiran Kumar, Tushar Sharma, Apress, 2016.

❖ Website: ocpjava.wordpress.com

❖ Amazon: http://amzn.com/1484218353