Chapter 15: Functional Programming Flashcards
Which functional interface from java.util.function takes 0 parameters and returns a generic object (T)?
Supplier
Which functional interface from java.util.function takes 1 parameter and returns void?
Consumer
Which functional interface from java.util.function takes 2 parameters and returns void?
BiConsumer
Which functional interface from java.util.function takes 1 parameter and returns a boolean?
Predicate
Which functional interface from java.util.function takes 2 parameters and returns a boolean?
BiPredicate
Which functional interface from java.util.function takes 1 parameter and returns a generic object (R)?
Function
Which functional interface from java.util.function takes 2 parameters (T, U) and returns a generic object (R)?
Function
Which functional interface from java.util.function takes 1 parameter (T) and returns a generic object (T)?
UnaryOperator
Which functional interface from java.util.function takes 2 parameters (T, T) and returns a generic object (T)?
BinaryOperator
When should the Supplier interface be used?
When you want to generate or supply values without taking any input.
What method does the Supplier functional interface have?
get()
When should the Consumer interface be used?
When you want to do something with a parameter but not return anything.
What method does the Consumer and BiConsumer functional interfaces have?
accept(T)
accept(T, U)
What method does the Predicate and BiPredicate functional interfaces have?
test(T)
test(T, U)
What method does the Function and BiFunction functional interfaces have?
apply(T)
apply(T, U)
When should the Function interface be used?
When you want to turn one parameter into a value of potentially different type and return it.
Which functional interface should be used when you want to combine two strings and return a new one?
BiFunction or BinaryOperator (better)
UnaryOperator and BinaryOperator are similar to Function and BiFunction. How do they differ?
UnaryOperator and BinaryOperator require the input and output to be of the same type.
What interface does UnaryOperator extend?
Function
What interface does BinaryOperator extend?
BiFunction
Is the following code valid?
UnaryOperator u1 = String::length;
No. The statement returns an Integer but UnaryOperator requires the return type be the same as the input type (String).
To make this code valid, Function needs to be used.
What functional interface would you use in the following situation:
Returns a String without taking any parameters.
Supplier
What functional interface would you use in the following situation:
Returns a Boolean (not a primitive) and takes a String
Function
Predicate returns a primitive boolean.
What functional interface would you use in the following situation:
Returns an Integer and takes two Integers.
BinaryOperator or BiFunction (both are equivalent, but BinaryOperator is more specific).