Programmer I Chapter 6: Lambdas and Functional Interfaces Flashcards

1
Q

in what order (asc, desc) would these sort?

Comparator strings = (s1, s2) -> s2.compareTo(s1);
Comparator moreStrings = (s1, s2) -> - s1.compareTo(s2);

A

Both of these comparators actually do the same thing: sort in descending order. In the first example, the call to compareTo() is“backwards,” making it descending. In the second example, the calluses the default order; however, it applies a negative sign to the result,which reverses it

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

Can you figure out the type of x?

public void whatAmI() {
consume((var x) -> System.out.print(x), 123);
}

public void consume(Consumer < Integer > c, int num) {
c.accept(num);
}

A

If you guessed Integer, you were right. The whatAmI() method creates a lambda to be passed to the consume() method. Since the consume()method expects an Integer as the generic, we know that is what the inferred type of x will be.

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

What do you think the type of x is here?

public void counts(List< Integer > list) {
list.sort((var x, var y) -> x.compareTo(y));
}

A

The answer is Integer. Since we are sorting a list, we can use the type of the list to determine the type of the lambda parameter.

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

Do you see what’s wrong here?

(a, b) -> { int a = 0; return 5;} // DOES NOT COMPILE

A

We tried to redeclare a, which is not allowed. Java doesn’t let you create a local variable with the same name as one already declared in that scope.

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

How many syntax errors do you see in this method?

11: public void variables(int a) {
12: int b = 1;
13: Predicate p1 = a -> {
14: int b = 0;
15: int c = 0;
16: return b == c;}
17: }

A

3
There are three syntax errors. The first is on line 13. The variable a was already used in this scope as a method parameter, so it cannot be reused. The next syntax error comes on line 14 where the code attempts to redeclare local variable b. The third syntax error is quite subtle and on line 16. See it? Look really closely.

The variable p1 is missing a semicolon at the end. There is a semicolon before the }, but that is inside the block. While you don’t normally have to look for missing semicolons, lambdas are tricky in this space,so beware!

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

is this code legal?

public class Crow {
   private String color;
   public void caw(String name) {
      String volume = "loudly";
      Consumer consumer = s ->
            System.out.println(name + " says "
                  \+ volume + " that she is " + color);
   }}
A

Legal.

This shows that lambda can access an instance variable, method parameter, or local variable under certain conditions. Instance variables (and class variables) are always allowed

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

what lines contain compilation errors?

2: public class Crow {
3: private String color;
4: public void caw(String name) {
5: String volume = “loudly”;
6: name = “Caty”;
7: color = “black”;
8:
9: Consumer consumer = s ->
10: System.out.println(name + “ says “
11: + volume + “ that she is “ + color);
12: volume = “softly”;
13: }
14: }

A

10, 11

In this example, name is not effectively final because it is set on line 6.However, the compiler error occurs on line 10. It’s not a problem to assign a value to a non final variable. However, once the lambda tries to use it, we do have a problem. The variable is no longer effectively final, so the lambda is not allowed to use the variable.

The variable volume is not effectively final either since it is updated online 12. In this case, the compiler error is on line 11. That’s before the assignment! Again, the act of assigning a value is only a problem from the point of view of the lambda. Therefore, the lambda has to be the-one to generate the compiler error.

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

what are the rules for accessing a variable from a lambda body inside a method?

Instance variable
Static variable
Local variable
Method variable
Lambda variable
A

Instance variable - Allowed
Static variable - Allowed
Local variable - Allowed if effectively final
Method variable - Allowed if effectively final
Lambda variable - Allowed

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

what will the list contain after running the code?

3: List < String > bunnies = new ArrayList<>();
4: bunnies.add(“long ear”);
5: bunnies.add(“floppy”);
6: bunnies.add(“hoppy”);
7: System.out.println(bunnies);
8: bunnies.removeIf(s -> s.charAt(0) != ‘h’);
9: System.out.println(bunnies);

A

[hoppy]

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

What is the result of the following class?

1: import java.util.function.*;
2:
3: public class Panda {
4: int age;
5: public static void main(String[] args) {
6: Panda p1 = new Panda();
7: p1.age = 1;
8: check(p1, p -> p.age < 5);
9: }
10: private static void check(Panda panda,
11: Predicate < Panda > pred) {
12: String result =
13: pred.test(panda) ? "match" : "not match";
14: System.out.print(result);
15: } }
A. match
B. not match
C. Compiler error on line 8.
D. Compiler error on lines 10 and 11.
E. Compiler error on lines 12 and 13.
F. A runtime exception is thrown.
A

A. This code is correct. Line 8 creates a lambda expression that checks whether the age is less than 5. Since there is only one parameter and it does not specify a type, the parentheses around the type parameter are optional. Lines 11 and 13 use the Predicateinterface, which declares a test() method.

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

What is the result of the following code?

1: interface Climb {
2: boolean isTooHigh(int height, int limit);
3: }
4:
5: public class Climber {
6: public static void main(String[] args) {
7: check((h, m) -> h.append(m).isEmpty(), 5);
8: }
9: private static void check(Climb climb, int height) {
10: if (climb.isTooHigh(height, 10))
11: System.out.println(“too high”);
12: else
13: System.out.println(“ok”);
14: }
15: }

A. ok
B. too high
C. Compiler error on line 7.
D. Compiler error on line 10.
E. Compiler error on a different line.
F. A runtime exception is thrown.
A

C. The interface takes two int parameters. The code on line 7attempts to use them as if one is a String. It is tricky to use types in a lambda when they are implicitly specified. Remember to check the interface for the real type.

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

Which of the following lambda expressions can fill in the blank?(Choose all that apply.)

List < String > list = new ArrayList<>();
list.removeIf(___________________);

A. s -> s.isEmpty()
B. s -> {s.isEmpty()}
C. s -> {s.isEmpty();}
D. s -> {return s.isEmpty();}
E. String s -> s.isEmpty()
F. (String s) -> s.isEmpty()
A

A, D, F. The removeIf() method expects a Predicate, which takes a parameter list of one parameter using the specified type. Options B and C are incorrect because they do not use the return keyword.This keyword is required to be inside the braces of a lambda body.Option E is incorrect because it is missing the parentheses around the parameter list. This is only optional for a single parameter with an inferred type.

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

Which lambda can replace the MySecret class to return the samevalue? (Choose all that apply.)

interface Secret {
String magic(double d);
}
class MySecret implements Secret {
public String magic(double d) {return "Poof";
}}

A. (e) -> “Poof”
B. (e) -> {“Poof”}
C. (e) -> { String e = “”; “Poof” }
D. (e) -> { String e = “”; return “Poof”; }
E. (e) -> { String e = “”; return “Poof” }
F. (e) -> { String f = “”; return “Poof”; }

A

A, F. Option B is incorrect because it does not use the return keyword. Options C, D, and E are incorrect because the variable e is already in use from the lambda and cannot be redefined. Additionally, option C is missing the return keyword, and option E is missing the semicolon

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

Which of the following lambda expressions can be passed to a function of Predicate < String > type? (Choose all that apply.)

A. () -> s.isEmpty()
B. s -> s.isEmpty()
C. String s -> s.isEmpty()
D. (String s) -> s.isEmpty()
E. (s1) -> s.isEmpty()
F. (s1, s2) -> s1.isEmpty()
A

B, D. Predicate takes a parameter list of one parameter using the specified type. Options A and F are incorrect because they specify the wrong number of parameters. Option C is incorrect because parentheses are required around the parameter list when the type is specified. Option E is incorrect because the name used in the parameter list does not match the name used in the body.

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

Which of these statements is true about the following code?

public void method() {
x((var x) -> {}, (var x, var y) -> 0);
}

public void x(Consumer < String > x, Comparator < Boolean > y)
{
}

A. The code does not compile because of one of the variables named x.
B. The code does not compile because of one of the variables named y.
C. The code does not compile for another reason.
D. The code compiles, and the var in each lambda refers to the same type.
E. The code compiles, and the var in each lambda refers to a different type.

A

E. While there appears to have been a variable name shortage when this code was written, it does compile. Lambda variables and method names are allowed to be the same. The x lambda parameter is scoped to within each lambda, so it is allowed to be reused. The type is inferred by the method it calls. The first lambda maps x to a String and the second to a Boolean. Therefore,option E is correct.

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

Which of the following will compile when filling in the blank?(Choose all that apply.)

List list = List.of(1, 2, 3);
Set set = Set.of(1, 2, 3);
Map map = Map.of(1, 2, 3, 4);
__________.forEach(x -> System.out.println(x));

A. list
B. set
C. map
D. map.keys()
E. map.keySet()
F. map.values()
G. map.valueSet()
A
A, B, E, F. 
The forEach() method with one lambda parameter works with a List or a Set. Therefore, options A and B are correct.Additionally, options E and F return a Set and can be used as well.Options D and G refer to methods that do not exist. Option C is tricky because a Map does have a forEach() method. However, it uses two lambda parameters rather than one.
17
Q

Which statements are true?

A. The Consumer interface is best for printing out an existingvalue.
B. The Supplier interface is best for printing out an existingvalue.
C. The Comparator interface returns an int.
D. The Predicate interface returns an int.
E. The Comparator interface has a method named test().
F. The Predicate interface has a method named test().

A

A, C, F. Option A is correct because a Supplier returns a value while a Consumer takes one and acts on it. Option C is correct because a Comparator returns a negative number, zero, or a positive number depending on the values passed. A Predicate always returns a boolean. It does have a method named test(),making option F correct.

18
Q

Which of the following can be inserted without causing a compilation error? (Choose all that apply.)

public void remove(List chars) {
char end = 'z';
chars.removeIf(c -> {char start = 'a'; return start <= c && c <= end; });
// INSERT LINE HERE
}
A. char start = 'a';
B. char c = 'x';
C. chars = null;
D. end = '1';
E. None of the above
A

A, B, C.
Since the scope of start and c is within the lambda, the variables can be declared after it without issue, making options A,B, and C correct. Option D is incorrect because setting end prevents it from being effectively final. Lambdas are only allowed to reference effectively final variables.

19
Q

How many lines does this code output?

Set < String > set = Set.of(“mickey”, “minnie”);
List < String > list = new ArrayList<>(set);
set.forEach(s -> System.out.println(s));
list.forEach(s -> System.out.println(s));

A. 0
B. 2
C. 4
D. The code does not compile.
E. A runtime exception is thrown.
A

C. Since the new ArrayList<>(set) constructor makes a copy of set, there are two elements in each of set and list. The forEach()methods print each element on a separate line. Therefore, four lines are printed, and option C is the answer.

20
Q

What is the output of the following code?

List < String > cats = new ArrayList<>();
cats.add(“leo”);
cats.add(“Olivia”);
cats.sort((c1, c2) -> -c1.compareTo(c2)); // line X
System.out.println(cats);

A. [leo, Olivia]
B. [Olivia, leo]
C. The code does not compile because of line X.
D. The code does not compile for another reason.
E. A runtime exception is thrown.

A

A. The code correctly sorts in descending order. Since uppercase normally sorts before lowercase, the order is reversed here, and option A is correct

21
Q

Which pieces of code can fill in the blanks? (Choose all that apply.)

______________ first = () -> Set.of(1.23);
______________ second = x -> true;

A. Consumer < Set < Double > >
B. Consumer < Set < Float > >
C. Predicate < Set < Double > >
D. Predicate < Set < Float > >
E. Supplier < Set < Double > >
F. Supplier < Set < Float > >
A

C, D, E. The first line takes no parameters, making it a Supplier.Option E is correct because Java can auto box from a primitive double to a Double object. Option F is incorrect because it is afloat rather than a double. The second line takes one parameter and returns a boolean, making it a Predicate. Since the lambda parameter is unused, any generic type is acceptable, and options C and D are both correct

22
Q

Which is true of the following code?

int length = 3;
for (int i = 0; i<3; i++) {
if (i%2 == 0) {
Supplier < Integer > supplier = () -> length; // A
System.out.println(supplier.get()); // B
} else {
int j = i;
Supplier < Integer > supplier = () -> j; // C
System.out.println(supplier.get()); // D
}}

A. The first compiler error is on line A.
B. The first compiler error is on line B.
C. The first compiler error is on line C.
D. The first compiler error is on line D.
E. The code compiles successfully.

A

E. Lambdas are only allowed to reference effectively final variables. You can tell the variable j is effectively final because adding a final keyword before it wouldn’t introduce a compile error. Each time the else statement is executed, the variable is redeclared and goes out of scope. Therefore, it is not re-assigned.Similarly, length is effectively final. There are no compile errors,and option E is correct

23
Q

Which of the following can be inserted without causing a compilation error? (Choose all that apply.)

public void remove(List < Character > chars) {
char end = 'z';
// INSERT LINE HERE
chars.removeIf(c -> {
char start = 'a'; return start <= c && c <= end; });
}
A. char start = 'a';
B. char c = 'x';
C. chars = null;
D. end = '1';
E. None of the above
A

C. Lambdas are not allowed to redeclare local variables, making options A and B incorrect. Option D is incorrect because setting end prevents it from being effectively final. Lambdas are only allowed to reference effectively final variables. Option C is tricky because it does compile but throws an exception at runtime. Since the question only asks about compilation, option C is correct.

24
Q

What is the output of the following code?

Set < String > cats = new HashSet<>();
cats.add("leo");
cats.add("Olivia");
cats.sort((c1, c2) -> -c1.compareTo(c2)); // line X
System.out.println(cats);

A. [leo, Olivia]
B. [Olivia, leo]
C. The code does not compile because of line X.
D. The code does not compile for another reason.
E. A runtime exception is thrown.

A

C. Set is not an ordered Collection. Since it does not have a sort() method, the code does not compile, making option C correct

25
Q

Which variables are effectively final? (Choose all that apply.)

public void isIt(String param1, String param2) {
String local1 = param1 + param2;
String local2 = param1 + param2;
param1 = null;
local2 = null;
}
A. local1
B. local2
C. param1
D. param2
E. None of the above
A

A, D. Method parameters and local variables are effectively final if they aren’t changed after initialization. Options A and D meet this criterion.

26
Q
What is the result of the following class?
1: import java.util.function.*;
2:
3: public class Panda {
4: int age;
5: public static void main(String[] args) {
6: Panda p1 = new Panda();
7: p1.age = 1;
8: check(p1, p -> {p.age < 5});
9: }
10: private static void check(Panda panda,
11: Predicate < Panda > pred) {
12: String result = pred.test(panda)
13: ? "match" : "not match";
14: System.out.print(result);
15: } }
A. match
B. not match
C. Compiler error on line 8.
D. Compiler error on line 10.
E. Compile error on line 12.
F. A runtime exception is thrown.
A

C. Line 8 uses braces around the body. This means the return keyword and semicolon are required

27
Q

Which lambda can replace the MySecret class? (Choose all that apply.)

interface Secret {
String concat(String a, String b);
}
class MySecret implements Secret {
public String concat(String a, String b) {
return a + b;
}}
A. (a, b) -> a + b
B. (String a, b) -> a + b
C. (String a, String b) -> a + b
D. (a, b) , a + b
E. (String a, b) , a + b
F. (String a, String b) , a + b
A

A, C. This interface specifies two String parameters. We can provide the parameter list with or without parameter types.However, it needs to be consistent, making option B incorrect.Options D, E, and F are incorrect because they do not use the arrow operator.

28
Q

Which of the following lambda expressions can be passed to a function of Predicate < String > type? (Choose all that apply.)

A. s -> s.isEmpty()
B. s --> s.isEmpty()
C. (String s) -> s.isEmpty()
D. (String s) --> s.isEmpty()
E. (StringBuilder s) -> s.isEmpty()
F. (StringBuilder s) --> s.isEmpty()
A

A, C. Predicate takes a parameter list of one parameter using the specified type. Options E and F are incorrect because it specifies the wrong type. Options B and D are incorrect because they use the wrong syntax for the arrow operator.

29
Q

How many lines does this code output?

Set < String > s = Set.of(“mickey”, “minnie”);
List < String > x = new ArrayList<>(s);
s.forEach(s -> System.out.println(s));
x.forEach(x -> System.out.println(x));

A. 0
B. 2
C. 4
D. The code does not compile.
E. A runtime exception is thrown.
A

D. Lambda parameters are not allowed to use the same name as another variable in the same scope. The variable names s and x are taken from the object declarations and therefore not available to be used inside the lambda.