Java Core: Lambdas (Functional Programming) Flashcards
What are functional interfaces? How can you create a functional interface?
A functional interface is an interface that has only one unimplemented method. It may have other methods but they must not be abstract.
A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
class Test { public static void main(String args[]) { // create anonymous inner class object new Thread(new Runnable() { @Override public void run() { System.out.println("New thread created"); } }).start(); } }
What is ‘Optional’, and how do you work with it?
An Optional is a class that acts as a container for an object. And when Optional is initialized, it should specify the type it can contain (Optional, for example). Its purpose is to represent objects which may be null rather than having just a null reference.
What are streams?
A stream() turns a list into a sequence of elements that come one after the other. One or several stream operations can be used on each streamed element.
Describe the following stream operation - ‘filter’
▪ Filter - select only elements that mach a given predicate (condition);
Describe the following stream operation - ‘map’
Map - convert or change an object;
Describe the following stream operation - ‘min’/’max’
Min/max - get the minimum or maximum value from the streamed elements (a comparator can be used to determine how this is decided);
Describe the following stream operation - ‘find’/’findFirst’
▪ Find/findFirst - find the first element in the stream;
Describe the following stream operation - ‘collect’
Collect - packages streamed elements into a specified data structure (.collect(Collectors.toList());
Describe the following stream operation - ‘ifPresent’
ifPresent - performs an operation to a streamed Optional only if the contained object is not null.
When would you use lambdas?
Lambda expressions simplify development by making several parts of Java syntax optional, such as type declaration pf a parameter, return keyword, curl braces, etc. They should be used to pass functionality as an argument for methods.
Do you think lambdas (or functional approach in general) can be overused?
(Open-ended question, but the general goal is to demonstrate a scenario where at least some people would say that the functional approach becomes overused.)
The purpose of Lambdas is to simplify development. If a lambda makes a code less readable (harder to understand) then it defeats the purpose of using it.
Describe the following stream operation - ‘forEach’
The forEach method is used to iterate through every element of the stream.