Programmer II Chapter 4: Functional Programming Flashcards

1
Q

What functional interface would you use in these three situations?

Returns a String without taking any parameters

Returns a Boolean and takes a String

Returns an Integer and takes two Integers

A

Supplier < String >
Function < String, Boolean >
BiFunction < Integer, Integer, Integer > or BinaryOperator < Integer >

The first one is a Supplier < String > because it generates an object and takes zero parameters. The second one is a Function < String,Boolean > because it takes one parameter and returns another type. It’s a little tricky.You might think it is a Predicate < String >. Note that a Predicate returns a boolean primitive and not a Boolean object. Finally, the third one is either a BinaryOperator < Integer > or aBiFunction < Integer,Integer,Integer > . Since BinaryOperator is a special case of BiFunction, either is a correct answer. BinaryOperator < Integer > is the better answer of the two since it is more specific.

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

What functional interface would you use to fill in the blank for these?

6: ____________ < List > ex1 = x -> ““.equals(x.get(0));
7: ____________ < Long > ex2 = (Long l) -> System.out.println(l);
8: ____________ < String, String > ex3 = (s1, s2) -> false;

A

Predicate
Consumer
BiPredicate

Line 6 passes one List parameter to the lambda and returns a boolean. This tells us that it is a Predicate or Function. Since the generic declaration has only one parameter, it is a Predicate.
Line 7 passes one Long parameter to the lambda and doesn’t return anything. This tells us that it is a Consumer.
Line 8 takes two parameters and returns a boolean. When you see a boolean returned, think Predicate unless the generics specify a Boolean return type. In this case, there are two parameters, so it is a BiPredicate.

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

Why do these lines not compile?

6: Function < List < String > > ex1 = x -> x.get(0); // DOES NOT COMPILE
7: UnaryOperator < Long > ex2 = (Long l) -> 3.14; // DOES NOT COMIPLE
8: Predicate ex4 = String::isEmpty; // DOES NOT COMPILE

A

Line 6 claims to be a Function. A Function needs to specify two generics—the input parameter type and the return value type. The return value type is missing from line 6, causing the code not to compile. Line 7 is a UnaryOperator, which returns the same type as it is passed in. The example returns a double rather than a Long, causing the code not to compile.
Line 8 is missing the generic for Predicate. This makes the parameter that was passed an Object rather than a String. The lambda expects a String because it calls a method that exists on String rather than Object. Therefore, it doesn’t compile.

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

What does this do?

Stream.generate(() -> "Elsa")
   .filter(n -> n.length() == 4)
   .sorted()
   .limit(2)
   .forEach(System.out::println);
A

It hangs until you kill the program or it throws an exception after running out of memory. sorted() waits until everything to sort is present. That never happens because there is an infinite stream.

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

What does this do?

Stream.generate(() -> "Elsa")
   .filter(n -> n.length() == 4)
   .limit(2)
   .sorted()
   .forEach(System.out::println);
A

It prints Elsa twice

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

What does this print?

    var infinite = Stream.iterate(1, x -> x + 1);
    infinite.limit(5)
       .peek(System.out::print)
       .filter(x -> x % 2 == 1)
       .forEach(System.out::print);
A

11233455
As the first element passes through, 1 shows up in the peek() and print(). The second element makes it past limit() and peek(), but it gets caught in filter(). The third and fifth elements behave like the first element. The fourth behaves like the second.

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

Which functional interface would you use to fill in the blank to make the following code compile?

var d = 1.0;
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ f1 = x -> 1;
f1.applyAsInt(d);
A

IntFunction, DoubleToIntFunction

You can see that the functional interface in question takes a double parameter and returns an int. You can also see that it has a single abstract method named applyAsInt. The DoubleToIntFunction and ToIntFunction meet all three of those criteria.

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

What does this print?

25: var cats = new ArrayList < String > ();
26: cats.add(“Annie”);
27: cats.add(“Ripley”);
28: var stream = cats.stream();
29: cats.add(“KC”);
30: System.out.println(stream.count());

A

3
Lines 25–27 create a List with two elements. Line 28 requests that a stream becreated from that List. Remember that streams are lazily evaluated. This means that the stream isn’tactually created on line 28. An object is created that knows where to look for the data when it is needed.On line 29, the List gets a new element. On line 30, the stream pipeline actually runs. The stream pipelineruns first, looking at the source and seeing three elements.

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

What could be the output of the following?

  var stream = Stream.iterate("", (s) -> s + "1");
  System.out.println(stream.limit(2).map(x -> x + "2"));
A. 12112
B. 212
C. 212112
D. java.util.stream.ReferencePipeline$3@4517d9a3
E. The code does not compile.
F. An exception is thrown.
G. The code hangs.
A

D.
No terminal operation is called, so the stream never executes. The first line creates an infinitestream reference. If the stream were executed on the second line, it would get the first two elementsfrom that infinite stream, “” and “1”, and add an extra character, resulting in “2” and “12”,respectively. Since the stream is not executed, the reference is printed instead.

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

What could be the output of the following?

  Predicate < String > predicate = s -> s.startsWith("g");
  var stream1 = Stream.generate(() -> "growl!");
  var stream2 = Stream.generate(() -> "growl!");
  var b1 = stream1.anyMatch(predicate);
  var b2 = stream2.allMatch(predicate);
  System.out.println(b1 + " " + b2);
A. true false
B. true true
C. java.util.stream.ReferencePipeline$3@4517d9a3
D. The code does not compile.
E. An exception is thrown.
F. The code hangs
A

F.
Both streams created in this code snippet are infinite streams. The variable b1 is set to true since anyMatch() terminates. Even though the stream is infinite, Java finds a match on the first element and stops looking. However, when allMatch() runs, it needs to keep going until the end of the stream since it keeps finding matches. Since all elements continue to match, the program hangs.

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

What could be the output of the following?

  Predicate < String > predicate = s -> s.length() > 3;
  var stream = Stream.iterate("-",
     s -> ! s.isEmpty(), (s) -> s + s);
  var b1 = stream.noneMatch(predicate);
  var b2 = stream.anyMatch(predicate);
  System.out.println(b1 + " " + b2);
A. false false
B. false true
C. java.util.stream.ReferencePipeline$3@4517d9a3
D. The code does not compile.
E. An exception is thrown.
F. The code hangs
A

E. An infinite stream is generated where each element is twice as long as the previous one. While thiscode uses the three-parameter iterate() method, the condition is never false. The variable b1 is setto false because Java finds an element that matches when it gets to the element of length 4. However,the next line tries to operate on the same stream. Since streams can be used only once, this throws anexception that the “stream has already been operated upon or closed.” If two different streams wereused, the result would be option B.

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

Which are true statements about terminal operations in a stream that runs successfully? (Choose all that apply.)

A. At most, one terminal operation can exist in a stream pipeline.
B. Terminal operations are a required part of the stream pipeline in order to get a result.
C. Terminal operations have Stream as the return type.
D. The peek() method is an example of a terminal operation.
E. The referenced Stream may be used after calling a terminal operation

A

A, B.
Terminal operations are the final step in a stream pipeline. Exactly one is required, because ittriggers the execution of the entire stream pipeline. Therefore, options A and B are correct. Option Cis true of intermediate operations, rather than terminal operations. Option D is incorrect becausepeek() is an intermediate operation. Finally, option E is incorrect because once a stream pipeline isrun, the Stream is marked invalid.

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

Which of the following sets result to 8.0? (Choose all that apply.)

A.
double result = LongStream.of(6L, 8L, 10L)
.mapToInt(x -> (int) x)
.collect(Collectors.groupingBy(x -> x))
.keySet()
.stream()
.collect(Collectors.averagingInt(x -> x));

B.
double result = LongStream.of(6L, 8L, 10L)
.mapToInt(x -> x)
.boxed()
.collect(Collectors.groupingBy(x -> x))
.keySet()
.stream()
.collect(Collectors.averagingInt(x -> x));
C.
double result = LongStream.of(6L, 8L, 10L)
.mapToInt(x -> (int) x)
.boxed()
.collect(Collectors.groupingBy(x -> x))
.keySet()
.stream()
.collect(Collectors.averagingInt(x -> x));
D.
double result = LongStream.of(6L, 8L, 10L)
.mapToInt(x -> (int) x)
.collect(Collectors.groupingBy(x -> x, Collectors.toSet()))
.keySet()
.stream()
.collect(Collectors.averagingInt(x -> x));

E.
double result = LongStream.of(6L, 8L, 10L) .mapToInt(x -> x)
.boxed()
.collect(Collectors.groupingBy(x -> x, Collectors.toSet()))
.keySet()
.stream()
.collect(Collectors.averagingInt(x -> x));F. double result = LongStream.of(6L, 8L, 10L)
.mapToInt(x -> (int) x)
.boxed()
.collect(Collectors.groupingBy(x -> x, Collectors.toSet()))
.keySet()
.stream()
.collect(Collectors.averagingInt(x -> x));

A

C, F.
Yes, we know this question is a lot of reading. Remember to look for the differences betweenoptions rather than studying each line. These options all have much in common. All of them start outwith a LongStream and attempt to convert it to an IntStream. However, options B and E are incorrectbecause they do not cast the long to an int, resulting in a compiler error on the mapToInt() calls.

Next, we hit the second difference. Options A and D are incorrect because they are missing boxed()before the collect() call. Since groupingBy() is creating a Collection, we need a nonprimitiveStream. The final difference is that option F specifies the type of Collection. This is allowed,though, meaning both options C and F are correct.

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

Which of the following can fill in the blank so that the code prints out false? (Choose all that apply.)

  var s = Stream.generate(() -> "meow");
  var match = s.\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_(String::isEmpty);
  System.out.println(match);
A. allMatch
B. anyMatch
C. findAny
D. findFirst
E. noneMatch
F. None of the above
A

A. Options C and D do not compile because these methods do not take a Predicate parameter and do not return a boolean. When working with streams, it is important to remember the behavior of the underlying functional interfaces. Options B and E are incorrect. While the code compiles, it runs infinitely. The stream has no way to know that a match won’t show up later. Option A is correct because it is safe to return false as soon as one element passes through the stream that doesn’t match.

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

We have a method that returns a sorted list without changing the original. Which of the following can replace the method implementation to do the same with streams?

  private static List < String > sort(List < String > list) {
     var copy = new ArrayList < String > (list);
     Collections.sort(copy, (a, b) -> b.compareTo(a));
     return copy;
  }

A.
return list.stream()
.compare((a, b) -> b.compareTo(a))
.collect(Collectors.toList());

B.
return list.stream()
.compare((a, b) -> b.compareTo(a))
.sort();

C.
return list.stream()
.compareTo((a, b) -> b.compareTo(a))
.collect(Collectors.toList());

D.
return list.stream()
.compareTo((a, b) -> b.compareTo(a))
.sort();

E.
return list.stream()
.sorted((a, b) -> b.compareTo(a))
.collect();

F.
return list.stream()
.sorted((a, b) -> b.compareTo(a))
.collect(Collectors.toList());

A

F. There is no Stream < T > method called compare() or compareTo(), so options A through D can beeliminated. The sorted() method is correct to use in a stream pipeline to return a sorted Stream. Thecollect() method can be used to turn the stream into a List. The collect() method requires acollector be selected, making option E incorrect and option F correct.

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

Which of the following are true given this declaration? (Choose all that apply.)

var is = IntStream.empty();

A. is.average() returns the type int.
B. is.average() returns the type OptionalInt.
C. is.findAny() returns the type int.
D. is.findAny() returns the type OptionalInt.
E. is.sum() returns the type int.
F. is.sum() returns the type OptionalInt

A

D, E. The average() method returns an OptionalDouble since averages of any type can result in afraction. Therefore, options A and B are both incorrect. The findAny() method returns anOptionalInt because there might not be any elements to find. Therefore, option D is correct. Thesum() method returns an int rather than an OptionalInt because the sum of an empty list is zero.Therefore, option E is correct.

17
Q

Which of the following can we add after line 6 for the code to run without error and not produce any output? (Choose all that apply.)

4: var stream = LongStream.of(1, 2, 3);
5: var opt = stream.map(n -> n * 10)
6: .filter(n -> n < 5).findFirst();

A. if (opt.isPresent())
   System.out.println(opt.get());
B. if (opt.isPresent())
   System.out.println(opt.getAsLong());
C. opt.ifPresent(System.out.println);
D. opt.ifPresent(System.out::println);
E. None of these; the code does not compile.
F. None of these; line 5 throws an exception at runtime.
A

B, D.
Lines 4–6 compile and run without issue, making option F incorrect. Line 4 creates a stream ofelements [1, 2, 3]. Line 5 maps the stream to a new stream with values [10, 20, 30]. Line 6filters out all items not less than 5, which in this case results in an empty stream. For this reason,findFirst() returns an empty Optional.

Option A does not compile. It would work for a Stream < T > object, but we have a LongStream andtherefore need to call getAsLong(). Option C also does not compile, as it is missing the :: that wouldmake it a method reference. Options B and D both compile and run without error, although neitherproduces any output at runtime since the stream is empty

18
Q

Given the four statements (L, M, N, O), select and order the ones that would complete the expression and cause the code to output 10 lines. (Choose all that apply.)

  Stream.generate(() -> "1")
     L: .filter(x -> x.length() > 1)
     M: .forEach(System.out::println)
     N: .limit(10)
     O: .peek(System.out::println)
  ;
A. L, N
B. L, N, O
C. L, N, M
D. L, N, M, O
E. L, O, M
F. N, M
G. N, O
A

F.
Only one of the method calls, forEach(), is a terminal operation, so any answer in which M is not the last line will not execute the pipeline. This eliminates all but options C, E, and F. Option C is incorrect because filter() is called before limit(). Since none of the elements of the stream meets the requirement for the Predicate < String > , the filter() operation will run infinitely, never passing any elements to limit(). Option E is incorrect because there is no limit() operation, which means that the code would run infinitely. Only option F is correct. It first limits the infinite stream to a finite stream of 10 elements and then prints the result.

19
Q

What changes need to be made together for this code to print the string 12345? (Choose all that apply.)

Stream.iterate(1, x -> x++)
.limit(5).map(x -> x)
.collect(Collectors.joining());

A. Change Collectors.joining() to Collectors.joining(“,”).
B. Change map(x -> x) to map(x -> “” + x).
C. Change x -> x++ to x -> ++x.
D. Add forEach(System.out::print) after the call to collect().
E. Wrap the entire line in a System.out.print statement.
F. None of the above. The code already prints 12345

A

B, C, E.
As written, the code doesn’t compile because the Collectors.joining() expects to get aStream < String > . Option B fixes this, at which point nothing is output because the collector creates aString without outputting the result. Option E fixes this and causes the output to be 11111. Since the post-increment operator is used, the stream contains an infinite number of the character 1. Option C fixes this and causes the stream to contain increasing numbers.

20
Q

Which functional interfaces complete the following code? For line 7, assume m and n are instances of functional interfaces that exist and have the same type as y. (Choose three.)

6: ________________ x = String::new;
7: ________________ y = m.andThen(n);
8: ________________ z = a -> a + a;

A. BinaryConsumer < String, String >
B. BiConsumer < String, String >
C. BinaryFunction < String, String >
D. BiFunction < String, String >
E. Predicate < String >
F. Supplier < String >
G. UnaryOperator < String >
H. UnaryOperator < String, String >
A

B, F, G. We can eliminate four choices right away. Options A and C are there to mislead you; theseinterfaces don’t actually exist. Option D is incorrect because a BiFunction < T,U,R > takes three genericarguments, not two. Option E is incorrect because none of the examples returns a boolean.

Moving on to the remaining choices, the declaration on line 6 doesn’t take any parameters, and itreturns a String, so a Supplier < String > can fill in the blank, making option F correct. Another clueis that it uses a constructor reference, which should scream Supplier! This makes option F correct.The declaration on line 7 requires you to recognize that Consumer and Function, along with theirbinary equivalents, have an andThen() method. This makes option B correct.

Finally, line 8 takes a single parameter, and it returns the same type, which is a UnaryOperator. Sincethe types are the same, only one generic parameter is needed, making option G correct.

21
Q

Which of the following is true?

List < Integer > x1 = List.of(1, 2, 3);
List < Integer > x2 = List.of(4, 5, 6);
List < Integer > x3 = List.of();
Stream.of(x1, x2, x3).map(x -> x + 1)
.flatMap(x -> x.stream())
.forEach(System.out::print);

A. The code compiles and prints 123456.
B. The code compiles and prints 234567.
C. The code compiles but does not print anything.
D. The code compiles but prints stream references.
E. The code runs infinitely.
F. The code does not compile.
G. The code throws an exception

A

F. If the map() and flatMap() calls were reversed, option B would be correct. In this case, the Stream created from the source is of type Stream < List > . Trying to use the addition operator (+) on a List isnot supported in Java. Therefore, the code does not compile, and option F is correct

22
Q

Which of the following is true? (Choose all that apply.)

4: Stream s = Stream.of(1);
5: IntStream is = s.boxed();
6: DoubleStream ds = s.mapToDouble(x -> x);
7: Stream s2 = ds.mapToInt(x -> x);
8: s2.forEach(System.out::print);

A. Line 4 causes a compiler error.
B. Line 5 causes a compiler error.
C. Line 6 causes a compiler error.
D. Line 7 causes a compiler error.
E. Line 8 causes a compiler error.
F. The code compiles but throws an exception at runtime.
G. The code compiles and prints 1
A

B, D. Line 4 creates a Stream and uses autoboxing to put the Integer wrapper of 1 inside. Line 5does not compile because boxed() is available only on primitive streams like IntStream, notStream < Integer > . Line 6 converts to a double primitive, which works since Integer can be unboxedto a value that can be implicitly cast to a double. Line 7 does not compile for two reasons. First,converting from a double to an int would require an explicit cast. Also, mapToInt() returns anIntStream so the data type of s3 is incorrect. The rest of the lines compile without issue

23
Q

Given the generic type String, the partitioningBy() collector creates a Map < Boolean,List < String > > when passed to collect() by default. When a downstream collector is passed topartitioningBy(), which return types can be created? (Choose all that apply.)

A. Map < boolean, List < String > >
B. Map < Boolean, List < String > >
C. Map < Boolean, Map < String > >
D. Map < Boolean, Set < String > >
E. Map < Long, TreeSet < String > >
F. None of the above
A

B, D. Options A and C do not compile, because they are invalid generic declarations. Primitives arenot allowed as generics, and Map must have two generic type parameters. Option E is incorrectbecause partitioning only gives a Boolean key. Options B and D are correct because they return a Mapwith a Boolean key and a value type that can be customized to any Collection.

24
Q

Which of the following statements are true about this code? (Choose all that apply.)

20: Predicate < String > empty = String::isEmpty;
21: Predicate < String > notEmpty = empty.negate();
22:
23: var result = Stream.generate(() -> “”)
24: .limit(10)
25: .filter(notEmpty)
26: .collect(Collectors.groupingBy(k -> k))
27: .entrySet()
28: .stream()
29: .map(Entry::getValue)
30: .flatMap(Collection::stream)
31: .collect(Collectors.partitioningBy(notEmpty));
32: System.out.println(result);

A. It outputs: {}
B. It outputs: {false=[], true=[]}
C. If we changed line 31 from partitioningBy(notEmpty) to groupingBy(n -> n), it would output: {}
D. If we changed line 31 from partitioningBy(notEmpty) to groupingBy(n -> n), it would output: {false=[], true=[]}
E. The code does not compile.
F. The code compiles but does not terminate at runtime

A

B, C.
First, this mess of code does compile. While this code starts out with an infinite stream on line 23, it does become finite on line 24 thanks to limit(), making option F incorrect. The pipeline preserves only nonempty elements on line 25. Since there aren’t any of those, the pipeline is empty.

Line 26 converts this to an empty map.Lines 27 and 28 create a Set with no elements and then another empty stream. Lines 29 and 30convert the generic type of the Stream to List < String > and then String. Finally, line 31 gives us another Map < Boolean, List < String > >.

The partitioningBy() operation always returns a map with two Boolean keys, even if there are no corresponding values. Therefore, option B is correct if the code is kept as is. By contrast, groupingBy() returns only keys that are actually needed, making option C correct if the code is modified on line 31

25
Q

Which of the following is equivalent to this code? (Choose all that apply.)

UnaryOperator < Integer > u = x -> x * x;

A. BiFunction < Integer > f = x -> xx;
B. BiFunction < Integer, Integer> f = x -> x
x;
C. BinaryOperator < Integer, Integer > f = x -> xx;
D. Function < Integer > f = x -> x
x;
E. Function < Integer, Integer > f = x -> x*x;
F. None of the above

A

E.
The question starts with a UnaryOperator < Integer > , which takes one parameter and returns a value of the same type. Therefore, option E is correct, as UnaryOperator actually extends Function.
Notice that other options don’t even compile because they have the wrong number of generic types for the functional interface provided. You should know that a BiFunction < T,U,R > takes three generic arguments, a BinaryOperator < T > takes one generic argument, and a Function < T,R > takes two generic arguments.

26
Q

What is the result of the following?

  var s = DoubleStream.of(1.2, 2.4);
  s.peek(System.out::println).filter(x -> x> 2).count();
A. 1
B. 2
C. 2.4
D. 1.2 and 2.4
E. There is no output.
F. The code does not compile.
G. An exception is thrown
A

D. The terminal operation is count(). Since there is a terminal operation, the intermediate operationsrun. The peek() operation comes before the filter(), so both numbers are printed. After thefilter(), the count() happens to be 1 since one of the numbers is filtered out. However, the result ofthe stream pipeline isn’t stored in a variable or printed, and it is ignored.

27
Q

What does the following code output?

Function < Integer, Integer > s = a -> a + 4;
Function < Integer, Integer > t = a -> a * 3;
Function < Integer, Integer > c = s.compose(t);
System.out.println(c.apply(1));

A. 7
B. 15
C. The code does not compile because of the data types in the lambda expressions.
D. The code does not compile because of the compose() call.
E. The code does not compile for another reason

A

A. The a.compose(b) method calls the Function parameter b before the reference Function variablea. In this case, that means that we multiply by 3 before adding 4. This gives a result of 7, makingoption A correct

28
Q

Which of the following functional interfaces contain an abstract method that returns a primitive value? (Choose all that apply.)

A. BooleanSupplier
B. CharSupplier
C. DoubleSupplier
D. FloatSupplier
E. IntSupplier
F. StringSupplier
A

A, C, E. Java includes support for three primitive streams, along with numerous functional interfacesto go with them: int, double, and long. For this reason, options C and E are correct. There is oneexception to this rule. While there is no BooleanStream class, there is a BooleanSupplier functionalinterface, making option A correct. Java does not include primitive streams or related functionalinterfaces for other numeric data types, making options B and D incorrect. Option F is incorrectbecause String is not a primitive, but an object. Only primitives have custom suppliers

29
Q

What is the simplest way of rewriting this code?
List < Integer > x = IntStream.range(1, 6)
.mapToObj(i -> i)
.collect(Collectors.toList());
x.forEach(System.out::println);

A. IntStream.range(1, 6);
B. IntStream.range(1, 6)
   .forEach(System.out::println);
C. IntStream.range(1, 6)
   .mapToObj(i -> i)
   .forEach(System.out::println);
D. None of the above is equivalent.
E. The provided code does not compile.
A

B. Both lists and streams have forEach() methods. There is no reason to collect into a list just to loop through it. Option A is incorrect because it does not contain a terminal operation or print anything.Options B and C both work. However, the question asks about the simpliest way, which is option B

30
Q

Which of the following throw an exception when an Optional is empty? (Choose all that apply.)

A. opt.orElse(“”);
B. opt.orElseGet(() -> “”);
C. opt.orElseThrow();
D. opt.orElseThrow(() -> throw new Exception());
E. opt.orElseThrow(RuntimeException::new);
F. opt.get();
G. opt.get(“”);

A

C, E, F.
Options A and B compile and return an empty string without throwing an exception, using a String and Supplier parameter, respectively. Option G does not compile as the get() method does not take a parameter. Options C and F throw a NoSuchElementException. Option E throws a RuntimeException. Option D looks correct but will compile only if the throw is removed.
Remember, the orElseThrow() should get a lambda expression or method reference that returns an exception, not one that throws an exception