Functional Interface Flashcards Preview

Review Java 8 > Functional Interface > Flashcards

Flashcards in Functional Interface Deck (20)
Loading flashcards...
1

What is a functional interface in Java 8?

As the name suggests, a functional interface is an interface that represents a function. Technically, an interface with just one abstract method is called a functional interface.

2

Examples of Functional Interface?

Runnable, Callable, Comparator, and Comparable from old API

Supplier, Consumer, and Predicate, etc. from new function API.

3

If a method accepts a functional interface, can you pass a lambda expression to it?

Yes

4

How to create a Functional Interface?

You can also use @FunctionalInterface to annotated a functional interface.

In that case, the compiler will verify if the interface actually contains just one abstract method or not.

It's like the @Override annotation, which prevents you from accidental errors.

5

What is a Predicate interface?

@FunctionalInterface
public interface Predicate

Represents a predicate (boolean-valued function) of one argument.

This is a functional interface whose functional method is test(Object).

A Predicate is a functional interface that represents a function, which takes an Object and returns a boolean.

It is used in several Stream methods like filter(), which uses Predicate to filter unwanted elements.

here is how a Predicate function looks like:

public boolean test(T object){
return boolean;
}

You can see it just has one test() method which takes an object and returns a boolean. The method is used to test a condition if it passes; it returns true otherwise false.

6

Supplier?

@FunctionalInterface
public interface Supplier

Represents a supplier of results.

There is no requirement that a new or distinct result be returned each time the supplier is invoked.

This is a functional interface whose functional method is get().

The Supplier is a functional interface that returns an object. It's similar to the factory method or new(), which returns an object.

The Supplier has get() functional method, which doesn't take any argument and return an object of type T. This means you can use it anytime you need an object.

7

Consumer Functional interface?

@FunctionalInterface
public interface Consumer

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

This is a functional interface whose functional method is accept(Object).

8

SAM?

Single Abstract Method

Any interface with a SAM(Single Abstract Method) is a functional interface, and its implementation may be treated as lambda expressions.

9

Java 8's default methods are abstract?

No

10

A functional interface may still have multiple default methods?

Yes

11

Function interface?

@FunctionalInterface
public interface Function {

R apply(T t);

default Function compose(Function super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}

default Function andThen(Function super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static Function identity() {
return t -> t;
}

A functional interface with a method that receives one value type T and returns another object type R


For Example:

Function intToString = Object::toString;
Function quote = s -> "'" + s + "'";

Function quoteIntToString = quote.compose(intToString);

assertEquals("'5'", quoteIntToString.apply(5));

12

Primitive Function Specializations?

Since a primitive type can’t be a generic type argument, there are versions of the Function interface for most used primitive types double, int, long, and their combinations in argument and return types:

IntFunction, LongFunction, DoubleFunction: arguments are of specified type, return type is parameterized
ToIntFunction, ToLongFunction, ToDoubleFunction: return type is of specified type, arguments are parameterized

DoubleToIntFunction, DoubleToLongFunction, IntToDoubleFunction, IntToLongFunction, LongToIntFunction, LongToDoubleFunction — having both argument and return type defined as primitive types, as specified by their names

13

A function that takes a short and returns a byte?

@FunctionalInterface
public interface ShortToByteFunction {

byte applyAsByte(short s);

}

14

Two-Arity(The number of arguments or operands a function or operation takes) Function Specializations

To define lambdas with two arguments, we have to use additional interfaces that contain “Bi” keyword in their names: BiFunction, ToDoubleBiFunction, ToIntBiFunction, and ToLongBiFunction.

BiFunction has both arguments and a return type generified, while ToDoubleBiFunction and others allow you to return a primitive value.

15

BiFunction Interface?

Interface BiFunction

Type Parameters:
T - the type of the first argument to the function
U - the type of the second argument to the function
R - the type of the result of the function

Represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function.

This is a functional interface whose functional method is apply(Object, Object).

16

Example of BiFunction interface in the standard API?

Map.replaceAll method, which allows replacing all values in a map with some computed value.

Map salaries = new HashMap<>();
salaries.put("John", 40000);
salaries.put("Freddy", 30000);
salaries.put("Samuel", 50000);

salaries.replaceAll((name, oldValue) ->
name.equals("Freddy") ? oldValue : oldValue + 10000);

17

UnaryOperator

@FunctionalInterface
public interface UnaryOperator
extends Function

Represents an operation on a single operand that produces a result of the same type as its operand. This is a specialization of Function for the case where the operand and result are of the same type.

This is a functional interface whose functional method is Function.apply(Object).

18

Consumer andThen() method

default Consumer andThen(Consumer super T> after)

Returns a composed Consumer that performs, in sequence, this operation followed by the after operation.

If performing either operation throws an exception, it is relayed to the caller of the composed operation.

If performing this operation throws an exception, the after operation will not be performed.

Parameters:
after - the operation to perform after this operation

Returns:
a composed Consumer that performs in sequence this operation followed by the after operation

19

Consumer example

// Consumer to multiply 2 to every integer of a list
Consumer > modify = list ->
{
for (int i = 0; i < list.size(); i++)
list.set(i, 2 * list.get(i));
};

// Consumer to display a list of integers
Consumer >
dispList = list -> list.stream().forEach(a -> System.out.print(a + " "));

List list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);

// using addThen()
modify.andThen(dispList).accept(list);
;

20

Legacy Functional Interfaces?

Not all functional interfaces appeared in Java 8. Many interfaces from previous versions of Java conform to the constraints of a FunctionalInterface and can be used as lambdas.

A prominent example is the Runnable and Callable interfaces that are used in concurrency APIs.

In Java 8 these interfaces are also marked with a @FunctionalInterface annotation. This allows us to greatly simplify concurrency code: