Lambda Flashcards
What is actually lambda?
It is quick implementation of an functional interface, a shortcut for compiler.
Compiler is implementing a anonymous class instead of lambda later.
What is functional interface?
It is any interface that has only one abstract method.
It can be marked with @FunctionalInterface, but it is not mandatory.
Is empty lambda valid?
Yes.
Eg. s -> {}
Is “var” allowed as type reference for lambda?
No, there is no context in using “var”. It can be used inside lambda, or as parameter type.
What methods are ignored when defined in functional interface?
equals()
hashCode()
toString()
Can modifiers be used with lambda parameters?
Yes.
Eg. (final var x, @Deprecated var y) ->x.compareTo(…
What are method references?
Quick implementation of functional interface and what will be ran in implementation of the interface method.
interface Test {
int test();
}
() -> Math.random()
Math::random
Test test = Math::random;
test.test();
What abstract method inside interface returns, so must method reference.
What are some of predefined utility functional interfaces?
Supplier
Consumer
BiConsumer
Predicate
BiPredicate
Function
BiFunction
Unary Operator
Binary Operator
Supplier?
- no parameters
- returns any type object
- get() method
Supplier< Integer > supplier = () -> 1;
Consumer?
- has any type parameter, generic
- no returns
- accept() method
- can be chained with andThen()
Consumer< Integer > consumer = System.out::println;
BiConsumer?
- has two any type parameters, generics
- no returns
- accept() method
- can be chained with andThen()
BiConsumer<Integer, String> biConsumer = (a, b) -> { System.out.println(a); };
Predicate?
- has any type parameter, generic
- has boolean return
- test() method
- can be chained with and(), negate(), or()
Predicate< Integer > predicate = x -> x > 5;
BiPredicate?
- has two any type parameters, generics
- has boolean return
- test() method
- can be chained with and(), negate(), or()
BiPredicate<Integer, Integer> biPredicate = (a, b) -> a < b
Function?
- has any type parameter generic (first generic, first parameter)
- has return of the generic defined type
- apply() method
- can be chained with compose()
Function<Integer, Integer> function = x -> x * 2
BiFunction?
- has two any type parameter generic
- has return of the generic defined type
- apply() method
- can be chained with compose()
BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;