1. Java 8: Lambda Expressions Flashcards
What is a Functional Interface?
A Functional Interface provides target types and method references for lambda expressions. A Functional Interface has a single abstract method (SAM) called the functional method for that interface.
True or False:
When creating a Functional Interface you should always annotate it with the @FunctionalInterface annotation.
False.
@FunctionalInterface is optional and not required. While it’s recommended to use the annotation the only use it has is to mark an interface as an Functional Interface and for the compiler to do some extra validations/checks when compiling.
Given the following code interfaces which ones will compile? 1. @FunctionalInterface public interface MyInterface { } 2. @FunctionalInterface public interface MyInterface { void doIt(); void doItNow(); } 3. @FunctionalInterface public interface MyInterface { default void doIt() {} static void doIts() {} void doItNow(); } 4. @FunctionalInterface public interface Comparator { int compare(T o1, T o2); boolean equals(Object obj); }
Will compile:
- Default and static methods in a Functional interface are allowed as long as there is one abstract method.
- Overriding public Object methods in a Functional interface does not count towards the interface’s abstract method count.
Will not compile:
1 will not compile because it doesn’t have a single abstract method.
2 will not compile because it has 2 abstract methods.
What is an default method in a interface?
You can define default methods (default keyword) inside interfaces, these methods do have a code body. These methods are inherited by implementing classes and can be overridden by these classes.
Given the following code: JButton button = ... JLabel label = ... button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { com.setText("Button has been clicked"); } });
And ActionListener is an interface with a single abstract method actionPerformed(ActionEvent e);
How would one rewrite this to make use of lambda’s?
button.addActionListener(e -> com.setText(“Button has been clicked”));
Given the following Lambda Expression and e is of type String:
e -> label.add(e);
How would this be rewritten with explicit type declaration.
(String e) -> label.add(e);
Given the following lambda expressions which ones are valid:
- s -> s.getAge() >= 18;
- s, a -> (s.getAge() || a.getAge()) >= 18;
- (Student s) -> s.getAge() >= 18;
- (s) -> s.getAge >= 18;
- (s, a) -> (s.getAge() || a.getAge()) >= 18;
1,3,4,5
2 not, if a function has multiple parameters they should be enclosed in parentheses.
When should you enclose a lambda body in braces?
When the body is not an expression but a statement and the statement should return a value.
What is the result of the following lambda:
email -> System.out.println(email);
Nothing, void methods doesn’t have to been enclosed in braces.