Chapter 6 Flashcards
What is a lambda expression?
A lambda expression is a short block of code which takes in parameters and returns a value.
What is an interface with one method called?
A functional interface
Name the four most used functional interfaces and their packages
- Predicate
- Consumer
- Supplier
- Comparator
When do you want to use the Predicate functional interface?
To test a method that returns a boolean value.
When do you want to use the Consumer functional interface?
When you want to do something without returning a value (such as printing something)
When do you want to use the Supplier functional interface?
The supplier takes zero parameters and thus is often used for generating values.
Is this code valid?
(a, b) -> { int a = 0; return 5; }
You cannot redeclare a, as a is already defined in the scope (parameter a).
Under what conditions are method parameters and local variables allowed to be referenced by a lambda expression?
If they are effectively final. (page 235)
What are the rules for accessing a variable from a lambda body inside a method?
- Instance variable: allowed
- Static variable: allowed
- Local variable: allowed if effectively final
- Method parameter: allowed if effictively final
- Lambda parameter: allowed
List and Set declare a removeIf() method. What functional interface does it take as a parameter?
A Predicate.
What functional interface does the method forEach() take as a parameter?
A Consumer.