8. Lambda Expressions and Functional Interfaces Flashcards
What does the flatmap expects?
The flatmap expects a function that will take on element and create a Stream out of it
What does the mapToDouble method expects?
The mapToDouble method expects a ToDoubleFunction object. that will take an argument and return a double
Consumer
Represents an operation that accepts a single input argument and returns no result
public interface Consumer{ void accept(T t); }
Consumer consumer = s -> System.out.println(s);
Supplier
Represents an operation that does not take any argument and returns any kind of object aslong as it matches the type.
public interface Supplier{ T get(); }
Supplier supplier =
() -> “Hello!;
Function
represents an operation that takes any object and may return any kind of object of another type.
public interface Function{ R apply(T t); }
Function getName =
user -> user.getName();
Predicate
represents an operation that takes any kind of object, test it and returns a boolean
public interface Predicate{ boolean test(T t); }
Predicate isEmpty =
s -> s.isEmpty();
What does the forEach method expects?
The forEach() method expects a consumer as an argument
What does the map’s forEach method expects?
The map’s forEach method requires a bifurcation, a function that takes two arguments
Do you need parentheses by the parameters in a lambda?
you can leave off the parantheses around the parameter, however if you have
more than one parameter you must use the parentheses.
do you need curly braces when returning an expression?
If you try to return a single expression without curly braces, your lambda expression won’t compile. But you can use it only in curly braces.
Can you acces variables of the enclosing scope?
A lambda expression captures variables from the ecnlosing scope, so you can access those variables in the body of the lambda, but those variables must be final or effectively final. An effectively final variable is a variable or parameter whose value isn’t changed after it is initialized. You can’t modify the values of an variable in the lambda expression, otherwise you get an error.
What does the @FuncionalInterface do?
We can explicity define a functional interface using the @FunctionalInterface annotation. This
annotation is not required but can be helpful when you want to ensure you don’t inadvertently add methods to a functional interface that will then break other code.
What are the 4 basic types of functional interfaces?
Supplier, Consumer, Predicate and Function
What are the variations on supplier?
IntSupplier, DoubleSupplier, LongSupplier. The functional method names of each of
these is different and is not get(), the funtional method of IntSupplier is getAsInt().
What are the variations on consumer?
IntConsumer, DoubleConsumer, LongConsumer, their
accept() methods take one primitive argument and avoid the autoboxing you get with consumer.