2. Java 8: Using Built-in Lambda Types Flashcards
Java 8 comes with some most-used functional interfaces, in which package are these interfaces hosted?
java.util.function
Name the functional interface that represents a boolean valued function of one argument that takes the type of T.
Predicate
public boolean test(T t)
Name the functional interface that represents a operation with no return value and accepts one argument of type T.
Consumer
public void accept(T t)
Name the functional interface that represents a function that returns a value of R and accepts one argument of type T.
Function
public R apply(T t);
Name the functional interface that is a supplier of values.
Supplier
public T get();
Name the functional interface that represents a function that produces a double result.
ToDoubleFunction
public double applyAsDouble(T t);
Name the functional interface that represents a boolean valued function of two arguments that takes the type of T and U.
BiPredicate
public boolean test(T t, U u);
Name the functional interface that represents a operation on a single argument that returns the same type as the argument.
UnaryOperator extends Function
public T apply(T t); // inherited from Function
Use the Function interface to create a Function that creates a new Boolean from a String. And then use that function to convert 3 strings to a Boolean:
true, false, dfa
Function function = s -> new Boolean(s);
s. apply(“true”); // true
s. apply(“false”); // false
s. apply(“dfa”); // false
Use the Consumer interface to loop over a String list and System.out their values. The list is calles values.
Consumer consumer = s -> System.out.println(s);
for(String value : values) {
s.accept(value);
}
Given the following class: class Book { String title; String author; // getters ommited public Book(title, author) {} }
How would one use the Supplier interface to create and return a new instance and print the title.
Supplier supplier = () -> new Book("title", "author"); System.out.println(supplier.get().getTitle());
How could you rewrite the following code to use a constructor reference? Supplier supplier = () -> new User();
Supplier supplier = User::new;
Use the UnaryOperator that takes a String and prints that with the addition of the string “ is Great!”.
UnaryOperator operator = s -> s + “ is Great!”;
Use the Predicate to print true when a String is larger then 5 characters.
Predicate predicate = s -> s.length() > 5;
System.out.println(predicate.test(“verylargestring”));
The usual FunctionalInterfaces only accept reference values as their parameters and return values. How can you use primitves in the FunctionalInterfaces so that no boxing and unboxing takes place?
Use the specialized interfaces for primitive types. For example given the Function interface there are additional interfaces for example:
IntFunction
IntToDoubleFunction