functional interfaces & lambda expressions Flashcards

1
Q

any interface that has exactly one abstract method is called …

A

a functional interface

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

abstract method

A

methods from e.g. an interface that has a signature but not an implementation (the class that implements the interface will define the method with its own implementation - don’t forget annotation @Override)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

is List a functional interface?

A

no - it does not have only one method, it has many methods. A functional interface must have one method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

can a developer create a new functional interface?

A

yes they can. Java libraries also provide many functional interfaces - they are called “the standard Java functional interfaces”. (we cover four in ATA)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the four functional interfaces from Java that are covered in ATA?

A

Function, Supplier, Consumer, Predicate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

To implement an interface the standard way…

A
  1. The class header declares which interface it’s implementing
  2. The class implementation overrides each abstract method
  3. Create and document entire class
    A great deal of effort just to use the single method inside!
    (hint: instead, use lambda expressions)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

lambda expressions provide…

A

a quick and easy way to implement a functional interface without expliciitly defining a class or even a formal method declaration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

syntax of a lambda expression

A
argument -> method implementation
or 
(arg1, arg2) -> method implementation
or
() -> method implementation
or
(arg(s)) -> {
     mulit-line method
     implementation
}
Because each functional interface contains exactly one abstract method, lambda expressions allow us to implement only that one method (following the arrow) to satisfy the interface. We don't need to creat a class, and since the interface has only one method, we don't even need to name it!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

three parts to lambda expression

A
  1. the method argument
  2. the arrow separator ->
  3. the method implementation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Function interface

A
public interface Function {
     R apply(T t);
}
takes an input object, returns an output object
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

why don’t we need to name the method we call in a lambda expression?

A

the lamda “operator” -> automatically calls the ONE method in the interface, that one method is defined on the right of the -> operator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Supplier interface

A
public interface Supplier {
     T get();
}
no input, returns an output
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Supplier examples

A
List participants = {"ace", "queen", "diamond"}
Random random = new Random();
Supplier randomIndex = 
() -> random.nextInt(participants.size());
------
public void callOnParticipant(Supplier index) {
     String person = participants.get(indexChooser.get());
     System.out.println("Hello " + person);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Supplier interface notes

A
  1. Supplier does not take input directly, but may access any variable within its scope
  2. called with empty parenthesis () -> the get method implementation
  3. it doesn’t “appear” to have a return but does!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

note on keyword ‘return’ in lambda expressions

A

if you drop the curly braces from your one-line method implementation, and the functional interface that your lambda expression is implementing has a return value, you drop the keyword return. (most common usage of a lambda)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

method reference

A

if your lambda expression simply calls a method, this syntax is a way to “compactify” it:
long form: key -> method(key) or item -> item==null etc
I. Reference to an instance method of a particular object: containingObject::instanceMethodName
e.g.: recommendationsServiceClient::getBookRecs
(from .build(CacheLoader.from(^^)
II. Reference to an instance method of an arbitrary object of a particular type: ContainingType::methodName
e.g.: list.removeIf(String::isEmpty)
III. Reference to a static method:
ContainingClass::staticMethodName
e.g.: list.removeIf(StringUtils::isBlank)
e.g.: PublishingConverter::toPublishRecord

17
Q

Consumer interface

A

public interface Consumer {
void accept;
}

18
Q

when are consumers used?

A

Consumers are commonly used when:

  1. performing an operation on each member of a data structure
  2. updating another data structure by calling Consumer on each element
19
Q

example of Consumer

A

List names = fetchNames();
names.forEach(name -> System.out.println(“name: “ + name);

(note: forEach(Consumer action) is a List method)
fancier:
Consumer fancyLambda = myString -> System.out.println(“Hello there “ + myString “, how are you today?”);
names.forEach(fancyLambda);

20
Q

Predicate interface

A
public interface Predicate {
     boolean test(T t);
}
21
Q

what is Predicate used for?

A

Predicate is often used to filter (in or out) elements from a data structure, or to conditionally perform some operation on elements of a data structure.

A Predicate performs a test on an objects, and specifies whether it meets a certain condition or not.

22
Q

examples of Predicate

A

value -> value == null;

list. removeIf(value -> value == null);
(note: removeIf(Predicate filter) is a list method, it removes all elements of the collection that satisfy the given predicate. this method returns true if any element was removed.)

23
Q

remove all palindromes from a list

A
List noPalindrome = fetchWords;
noPalidrome.removeIf(text -> {
  String reverse = new StringBuffer(text).reverse.toString();
  return text.equals(reverse);
});

note:
1. with only one input, don’t need parentheis
2. the Predicate’s test(T t) method is inside the {} since multiple lines
3. the removeIf has regular parentheses () and end with ;
4. needs return since multiline (single line skips explicit return statement, it’s implied)
- ->( t -> { blabla; return boolean} );

If the input “satisfies the predicate” - means the test(input) returns true - the item is removed from the list.
**removeIf is a Collections method, which List inherits, so any collection can do this

24
Q

can a Predicate have two inputs

A

no - the signature test(T t) accounts for one input

25
Q

remove palindromes from list, defined as variable Predicate

A

Predicate noPalindrone = text -> {
String reverse = new StringBuffer.reverse().toString();
return text.equals(reverse);
};

question: is the ‘;’ correct at end?

26
Q

Function to open a file for reading data

A
Function fileOpener =
  filename -> {
      File file = new File(filename);
      try {
         return new FileInputStream(file); 
      } catch (FileNotFoundException e) {
         throw new IllegalArgumentException(e.getMessage..
      }
};
27
Q

Checked exceptions in lambda expressions

A

lamda cannot throw checked exceptions (not in the interface signature). What you need to do is use a try/catch block and throw a runtime exception.

e.g.: catch a FileNotFoundException (is a checked exception) and throw new IllegalArgumentException (is a runtime exception)
alternatively: just log it (dangerous): logger.warn(“Can’t open missing file: “ + filename);
return null; //maybe return a default file?

“make sure you plan for handling checked exceptions”