Functional Interface Flashcards

1
Q

What is a functional interface in Java 8?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Examples of Functional Interface?

A

Runnable, Callable, Comparator, and Comparable from old API

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to create a Functional Interface?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a Predicate interface?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Supplier?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Consumer Functional interface?

A

@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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

SAM?

A

Single Abstract Method

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Java 8’s default methods are abstract?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

A functional interface may still have multiple default methods?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Function interface?

A

@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));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Primitive Function Specializations?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

A function that takes a short and returns a byte?

A

@FunctionalInterface
public interface ShortToByteFunction {

byte applyAsByte(short s);

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

BiFunction Interface?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Example of BiFunction interface in the standard API?

A

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
Q

UnaryOperator

A

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

Consumer andThen() method

A

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
Q

Consumer example

A
// 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
Q

Legacy Functional Interfaces?

A

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: