Java OCP Part4. Functional programming

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Which of the following lambda expressions can be passed to a method that takes IntFunction<Integer> as an argument? (Choose all that apply) A. (Integer f) -> f B. (v) -> null C. s -> s D. None of the above

B, C To start with, IntFunction<Integer> takes an int value and returns an Integer. A uses Integer instead of int as the input argument and is therefore not compatible. B is compatible, since the return type null can be used as an Integer return type. C is also valid. An int can be autoboxed to Integer.

private static void spot(____________ x) { x.filter(y -> ! y.isEmpty()) .map(y -> 8) .ifPresent(System.out::println); } // Which of the following can be the type for x? (Choose all that apply) A. List<String> B. Optional<Collection> C. Optional<String> D. Stream<Collection> E. None of above

B, C. List doesn't have a filter() method, so Option A is incorrect. Stream does have filter() and map() methods. However, Stream doesn't have an ifPresent() method. This makes D incorrect so Options B and D are incorrect. Both Collection and String have an isEmpty() method, so either can be used with the Optional, making Option C the answer.

What java.util.function and java.util.stream package interface(s) would you use if you wanted to efficiently process a large number of temperature measurements represented by primitive double values and avoid autoboxing values? (Choose all that apply.) A. Consumer<Double> B. Supplier<Double> C. DoubleStream D. DoubleFunction E. Stream<Double> F. Function<Double, Double> G. DoubleUnaryOperator

C, D, G. All these interfaces are used with primitive double values.

DoubleStream ds = DoubleStream.of(406.0,407.2,408.1,406.5,407.8); OptionalDouble m = ds.filter(ppm -> ppm > 409.0).min(); System.out.println(m.getAsDouble()); What is the result? (Choose all that apply.) A. 409.0 B. 0.0 C. m is an empty optional D. Code does not compile E. A NoSuchElementException runtime exception

C, E. C = m is an empty optional because min() returns an optional and the stream is empty when we call min(). E = We are trying to get a value from m without checking first to make sure there's a value present.

Which two can independently fill in the blank to output "No dessert today" ? public class Dessert {public static void main(String[] yum) { eatDessert(Optional.empty()); } private static void eatDessert(Optional<String> opt) { System.out.println(opt.__________); } } A. get("No dessert today") B. get( () -> "No dessert today") C. orElse("No dessert today") D. orElse( () -> "No dessert today") E. orElseGet("No dessert today") F. orElseGet( () -> "No dessert today")

C, F. The Optional does not contain a value. While there is a get() method onOptional, it doesn't take any parameters, making Options A and B incorrect. Option C is the simplest way to print the desired result. The orElse() method returns the parameter passed if the Optional is empty. The orElseGet() method runs the Supplier passed as a parameter, making Option F correct as well.

Given the code fragment: *// LineX* double readings[] = { 408.7, 409.9, 410.2, 401.9, 410.1, 409.5 }; for (double r : readings) { c.accept(r); } Which code fragment(s), inserted independently at *LineX*, prints: New record! 410.2 New record! 410.1 (Choose all that apply.) *A.* Consumer c = d -> { if (d > 410) { System.out.println("New record! " + d); } }; *B.* DoubleFunction c = d -> { if (d > 410) { System.out.println("New record! " + d); } return d; }; *C.* DoubleConsumer c = d -> { if (d > 410) { System.out.println("New record! " + d); } }; *D.* Consumer<Double> c = d -> { if (d > 410) { System.out.println("New record! " + d); } }; *E.* Consumer<Double, Double> c = d -> { if (d > 410) { System.out.println("New record! " + d); } return d; };

C,D. Either DoubleConsumer (primitive version of Consumer) or Consumer<Double> will work. We know we need a Consumer, because we are using the accept() method on c. If D, then the double values get autoboxed to Doubles. A, B, and E are incorrect. In A, the Consumer expects type Object. In B, we need a Consumer, not a DoubleFunction for where we call the accept() functional method. In E Consumers do not return a value.

1: public class TicketTaker { 2: private static int AT_CAPACITY = 100; 3: public int takeTicket(int cur, IntUnaryOperator<Integer> counter) { 4: return counter.applyAsInt(cur); 5: } 6: public static void main(String...theater) { 7: final TicketTaker bob = new TicketTaker(); 8: final int old = 50; 9: final int new = bob.takeTicket(old, t -> { 10: if(t>AT_CAPACITY) { 11: throw new RuntimeException("Sorry, max has been reached"); 12: } 13: return t+1; 14: }); 15: System.out.print(new); } } // What is the output ? A. 51 B. The code does not compile because of lambda expression. (rows 9:14) C. The code does not compile for a different reason. D. The code compiles but prints an exception at runtime.

C. The IntUnaryOperator functional interface is not generic, so the argument IntUnaryOperator<Integer> does not compile, so Options A and D are incorrect. The lambda expression compiles without issue, making Option B incorrect. If the generic argument <Integer> was dropped from the argument declaration, the class would compile without issue and output 51 at runtime, making Option A the correct answer.

public class DogSearch { void reduceList(List<String> names, Predicate<String> tester) { names.removeIf(tester); } public static void main(String[] treats) { int MAX_LENGTH = 2; List<String> names = Arrays.asList("Lassie","Benji","Brian"); MAX_LENGTH += names.size(); new DogSearch().reduceList(names, d -> d.length()>MAX_LENGTH); System.out.print(names.size()); } } // What is the output? A. 2 B. 3 C. The code does not compile because of lambda expression. D. The code does not compile for a different reason. E. Exception will be thrown

C. The code does not compile, because the local variable MAX_LENGTH is neither final nor effectively final, meaning it cannot be used inside the lambda expression.

What is the output of this code? Stream<Boolean> bools = Stream.iterate(true,b-> !b); Map<Boolean, List<Boolean>> map = bools.limit(1).collect( partitioningBy(b -> b) ); System.out.println(map); A. {true=[true]} B. {false=null, true=[true]} C. {false=[], true=[true]} D. None of the above

C. The first intermediate operation, limit(1) , turns the infinite stream into a stream with one element: true. The partitioningBy() method returns a map with two keys,true and false, regardless of whether any elements actually match. If there are no matches, the value is an empty list, making Option C correct.

public class Catch { public static void main(String[] args) { Optional opt = Optional.empty(); try { apply(opt); } catch (IllegalArgumentException e) { System.out.println("Caught it"); } } private static void apply(Optional<Exception> opt) { opt.__________(IllegalArgumentException::new); } } // Which can fill in the blank so this code outputs Caught it ? A. orElse B. orElseGet C. orElseThrow D. None of the above. The main() method does not compile.

C. The main() method has warnings, but it does compile, making Option D incorrect.The warnings are both about not declaring the generic type for Optional. Option A does not compile because the orElse() method expects an Exception as the alternate value passed as a parameter. IllegalArgumentException::new is a Supplier instead. Options B and C both compile as both methods expect a Supplier as the parameter. However, orElseGet() simply returns the exception from the method rather than throwing it. Option C actually throws the exception the Supplier created and is the correct answer.

Assume R is a generic type, write return types for followed functional interfaces: DoubleConsumer IntFunction LongSupplier ObjDoubleConsumer

void, R, long, void All Consumer functional interfaces have a void return type. For this reason, the first and last values in the list are both void. IntFunction takes an int and returns a generic value, while LongSupplier does not take any values and returns a long value.

Write number of parameters for followed functional interfaces: DoubleConsumer, IntFunction, LongSupplier, ObjDoubleConsumer

1, 1, 0, 2 Remember that all Supplier interfaces take zero parameters. For this reason, the third value in the table is 0. Next, DoubleConsumer and IntFunction each take one value, double and int, respectively. On the other hand, ObjDoubleConsumer takes two values, a generic value and a double, and returns void.

What do you think this outputs? List<String> cats = new ArrayList<>(); cats.add("Annie"); cats.add("Ripley"); Stream<String> stream = cats.stream(); cats.add("KC"); System.out.println(stream.count());

3 The stream pipeline evaluated only when actually runs.

Function<String, Integer> f1 = String::length; System.out.println(f1.apply("cluck")); ?

5

Which of the following can fill in the blank so that the code prints out false? Stream<String> s = Stream.generate(() -> "meow"); boolean 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 is correct because it is safe to return false as soon as one element passes through the stream that doesn't match.

class Button { String title; public Button(String t) { this.title = t; } public void onClick(Supplier s) { System.out.println(s.get()); } } Button b = new Button("Click me"); *// L1* Which code fragment(s), inserted independently at *L1*, will result in the string "You clicked on me!" being printed to the console? (Choose all that apply.) A. b.onClick(() -> { return "You clicked on me!"; }); B. b.onClick(function() { return "You clicked on me!" }); C. Supplier p = () -> System.out.println("You clicked on me!"); b.onClick(p); D. b.onClick(() -> "You clicked on me!"); E. b.onClick((() -> "You clicked on me!").apply());

A and D. Both are Suppliers, which is what the onClick() method expects. Note the return and the { } in A are not necessary for this example, but will work fine. B, C, and E are incorrect based on the above. B and E are invalid syntax. C passes a Supplier, but the Supplier needs to return a value, and it prints a value instead.

Which of the following could you use to multiply 202 by 3 to get the result 606? (Choose all that apply.) A. IntStream.iterate(3, i -> i + 3).limit(202).max().getAsInt(); B. Stream.iterate(3, i -> i + 3).limit(202) .mapToInt(i->i).max().getAsInt(); C. Stream.generate(() -> 3 * 202).limit(1).findFirst().get(); D. IntStream.of(202, 202, 202).sum(); E. Stream.of(202, 202, 202).mapToInt(i->i).sum(); F. IntStream.of(202, 202, 202).reduce(0, (r1, r2) -> r1 + r2);

A, B, C, D, E, and F are correct. All of these solutions multiply 202 * 3 to get 606, just in different ways.

Which of the following return primitives? A. BooleanSupplier B. CharSupplier C. DoubleSupplier D. FloatSupplier E. IntSupplier F. StringSupplier

A,C,E

What are the necessary parts of every stream pipeline? (Choose all that apply.) A. A source B. A filter C. An intermediate operation D. A map E. A terminal operation F. A reduction operation

A,E. A stream pipeline consists of a source, zero or more intermediate operations (filter and map are intermediate operations), and a terminal operation (which may or may not be a reduction operation). B, C, D, and F are incorrect. In F while all reduction operations are terminal operations, you are not required to reduce a stream (you could, for instance, use a forEach() to terminate the stream and do nothing with the elements from the stream).

Which functional interface returns a primitive value? A. BiPredicate B. CharSupplier C. LongFunction D. UnaryOperator

A. Option A is the correct answer because BiPredicate takes two generic types and returns a primitive boolean value. Option B is incorrect, since CharSupplier does not exist. Option C is also incorrect, since LongFunction takes a primitive long value and returns a generic type. Remember, Java only includes primitive functional interfaces that operate on double, int, or long. Finally, Option D is incorrect. UnaryOperator takes a generic type and returns a generic value.

Stream<String> s = Stream.of("speak", "bark", "meow", "growl"); BinaryOperator<String> merge = (a, b) -> a; Map<Integer, String> map = s.collect( toMap( String::length, k -> k, merge ) ); System.out.println( map.size() + " " + map.get(4) ); // What is the output ? A. 2 bark B. 2 meow C. 4 bark D. None of the above

A. This code does compile. Remember that imports are implied, including the static import for Collectors. The collector tries to use the number of characters in each stream element as the key in a map. This works fine for the first two elements, 'speak' and 'bark' , because they are of length 5 and 4, respectively. When it gets to 'meow', it sees another key of 4. The merge function says to use the first one, so it chooses 'bark' for the value. Similarly, 'growl' is 5 characters, but the first value of 'speak' is used. There are only two distinct lengths 4 and 5, so Option A is correct.

class Toy { double price; String color; Toy(String color, double price) { this.color = color; this.price = price; } } // getters omitted List<Toy> toys = new ArrayList<>(); toys.add( new Toy("red", 10) ); toys.add( new Toy("yellow", 10) ); toys.add( new Toy("red", 10) ); double totalPrice = toys.stream() .filter(e -> e.getColor() == "red").*L1*.sum(); // Which code fragment can be inserted at *L1* to calc price of Red toys=20.0? A) .flatMap(e -> e.getPrice()) B) .mapToDouble(e -> e.getPrice()) C) .map(e -> e.getPrice()) D) .peek(e -> e.getPrice())

B Note that C isn't allowed because otherwise will be Stream<Double> which doesn't have a method .sum().

Which could insert independently at line *L1* so that prints flowers for May or June? (Choose all that apply.) class Bloom { String name; String month; public Bloom(String n, String m) { this.name = n; this.month = m; } // Getters here public String toString() { return name + ": " + month; } } // and the code fragment: List<Bloom> flowers = new ArrayList<>(); flowers.add(new Bloom("Apple", "May")); flowers.add(new Bloom("Zinnia", "May")); flowers.add(new Bloom("Cosmos", "July")); flowers.add(new Bloom("Heather", "June")); flowers.add(new Bloom("Allium", "August")); *// L1* springFlowers.forEach( (b, f) -> { if (b) { System.out.print(f + " "); } } ); A. List<Bloom> springFlowers = flowers.stream().collect(Collectors.toList(Bloom::getMonth) ); B. Map<Boolean, List<Bloom>> springFlowers = flowers.stream().collect( Collectors.groupingBy ( f -> f.getMonth().equals("May") || f.getMonth().equals("June") ) ); C. Map<Boolean, List<Bloom>> springFlowers = flowers.stream().collect(Collectors.partitioningBy( f -> f.getMonth().equals("May") || f.getMonth().equals("June") ) ); D. List<Bloom> springFlowers = flowers.stream().collect(Collectors.toList( f -> f.getMonth().equals("May") || f.getMonth().equals("June") ) );

B,C. In B, we are passing a Function to groupingBy() that groups flowers by a Boolean value in the Map: true if the flowers bloom in May or June. In C, we are passing a Predicate to partitioningBy() that groups flowers in the same way. Both will work! A and D are incorrect. Both are invalid ways to use toList().

Which of the following statements about functional interfaces is true? A. It is possible to define a functional interface that returns two data types. B. It is possible to define a primitive functional interface that uses float, char, or short. C. It is not possible to define a functional interface that does not take any arguments nor return any value. D. None of the primitive functional interfaces include generic arguments.

B. Java only supports a single return data type or void. Therefore, it is not possible to define a functional interface that returns two data types, making Option A incorrect. Although Java does not include built-in support for primitive functional interfaces that include float, char, or short, there is nothing to prevent a developer from creating them in their own project, making Option B the true statement and the correct answer. Option C is incorrect because a functional interface that takes no values and returns void is possible. In fact, Runnable is one such example. Option D is also incorrect, since IntFunction<R> takes a primitive argument as input and a generic argument for the return type.

Which expression is compatible with the IntSupplier functional interface? A. () -> 1<10 ? "3" : 4 B. () -> {return 1/0;} C. () -> return 4 D. System.out::print

B. Option A is incorrect because the String "3" is not compatible with the return type int required for IntSupplier. Option B is the correct answer. Although this will result in a divide by zero issue at runtime, the lambda is valid and compatible with IntSupplier. Option C is incorrect because the lambda expression is invalid. The return statement is only allowed inside a set of brackets {}. Finally, Option D is incorrect. The method reference is used for Supplier, not Consumer, since it takes a value and does not return anything.

Which functional interface does not have the correct number of generic arguments? A. BiFunction<T,U,R> B. DoubleFunction<T,R> C. ToDoubleFunction<T> D. ToIntBiFunction<T,U>

B. The BiFunction interface takes two different generic values and returns a generic value, taking a total of three generic arguments. Next, ToDoubleFunction takes exactly one generic value and returns a double value, requiring one generic argument. The ToIntBiFunction interface takes two generic values and returns an int value, for a total of two generic arguments. For these reasons, Options A, C, and D have the correct number of generic arguments.

Which of the following is a valid functional interface in the java.util.function package? A. FloatPredicate B. ToDoubleBiFunction C. UnaryIntOperator D. TriPredicate

B. The java.util.function package does not include any functional interfaces that operate on the primitive float, making Option A incorrect. Remember, Java only includes primitive functional interfaces that operate on double, int, or long. Option B is correct because it is a valid functional interface. Option C is incorrect because there is no UnaryIntOperator functional interface. Note that there is one called IntUnaryOperator. Option D is incorrect. The java.util.function package does not include any tri-operators, although many are easy to write.

public class Asteroid { public void mine(____________ lambda) { // TODO: Apply functional interface } public static void main(String[] debris) { new Asteroid().mine((s,p) -> s+p); } } // Which functional interface, when filled into the blank, allows the class to compile? A. BiConsumer<Integer,Double> B. BiFunction<Integer,Double,Double> C. BiFunction<Integer,Integer,Double> D. Function<Integer,Double>

B. The lambda (s,p) -> s+p takes two arguments and returns a value. For this reason, Option A is incorrect because BiConsumer does not return any values. Option D is also incorrect, since Function only takes one argument and returns a value. This leaves us with options B and C, which both use BiFunction, which takes two generic arguments and returns a generic value. Option C is incorrect because the datatype of the unboxed sum s+q is int and int cannot be autoboxed or implicitly cast to Double. Option B is correct. The sum s+p is of type double, and double can be autoboxed to Double.

class Temp implement Comparable<Temp> {...} Comparator<Temp> tempComp = ( (t1,t2) -> t1.getTemp().compareTo(t2.getTemp() ) ); And List<Temp> tempList filled with values; Which is correct type should be inserted to code: *<TYPE here>* max = tempList.stream.max( tempComp ); A. Optional<Double> B. Optional<Temperature> C. OptionalDouble D. Temperature E. Double F. double

B. max() takes a Comparator, which takes two Temperature objects and compares them using the temp field, producing Optional with the maximum Temperature object in the List.

public class Warehouse { private int quantity = 40; private final BooleanSupplier stock = () -> quantity>0; public void checkInventory() { if( stock.get() ) System.out.print("Plenty!"); else System.out.print("On Backorder!"); } public static void main(String... widget) { final Warehouse w13 = new Warehouse(); w13.checkInventory(); } } // What is the output ? A. Plenty! B. On Backorder! C. The code does not compile because of the checkInventory() method. D. The code does not compile for a different reason.

C. The primitive Supplier functional interfaces, such as BooleanSupplier and LongSupplier , do not have a get() method. Instead, they have methods such as getAsBoolean() and getAsLong(), respectively. For this reason, the first line of the checkInventory() method does not compile, making Option C the correct answer. If the method call was changed to getAsBoolean(), then the rest of the code would compile without issue, print 'Plenty!' at runtime, and Option A would be the correct answer.

Stream<Integer> is = Stream.of(8, 6, 9); Comparator<Integer> c = (a, b) -> a-b; is.sort(c).forEach(System.out::print); What is the output? A. 689 B. 986 C. The code does not compile D. The code compiles but throws an exception at runtime.

C. There is not a stream pipeline method called sort(). There is one called sorted(). Since the code does not compile, Option C is correct. If this was fixed, Option A would be correct answer

Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); String result = ohMy.collect( Collectors.joining(", ") ); System.out.println(result); // What is the output? A. Code won't compile B. The application hang forever C. Print "lions, tigers, bears" D. Compile but throw runtime exception

C. We pass the predefined joining() collector to the collect() method. All elements of the stream are then merged into a String with the specified delimiter between each element. So it prints "lions, tigers, bears". Notice how the predefined collectors are in the Collectors class rather than the Collector class.

public class Doll { private int layer; public Doll(int layer) { this.layer = layer; } public static void open(UnaryOperator<Doll> task, Doll doll) { while( ( doll = task.accept(doll) ) != null ) { System.out.print("X"); } } public static void main(String[] wood) { open(s -> { if(s.layer<=0) return null; else return new Doll(s.layer--); } , new Doll(5) ); } } // What is the output ? A. X B. The code does not compile because of the lambda expression. C. The code does not compile for a different reason. D. The code compiles but produces an infinite loop at runtime.

C. The task variable is of type UnaryOperator<Doll>, with the abstract method apply(). There is no accept() method defined on that interface, therefore the code does not compile, and Option C is the correct answer. If the code was corrected to use the apply() method, the rest of it would compile without issue. At runtime, it would then produce an infinite loop.

What is the output of the following? Stream<String> 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.

D No terminal operation is called, so the stream never executes.

Given the following code fragment: *___________* tt = (a, b) -> { *// line 1* return axa + bxb; }; int ss = tt.*_____________*(2, 3); *// line 4* System.out.println("Sum of squares: " + ss); Which one of the following would you insert in *line 1* (the type) and *line 4* (the method name) so that the code fragment compiles, runs, and produces the output 13? A. IntBinaryOperator, apply B. BiFunction<Integer, Integer>, apply C. IntBinaryOperator, accept D. IntBinaryOperator, applyAsInt E. BinaryOperator<Integer>, apply

D,E. The lambda expression takes two ints and returns an int (on line 4), so an IntBinaryOperator is appropriate (D). The abstract method in the IntBinaryOperator functional interface is applyAsInt. E also works because the primitive ints are autoboxed and unboxed. If you want to avoid autoboxing, D is the better solution. A, B, and C are incorrect. A is incorrect; applyis not the correct function name for a primitive functional interface. B is incorrect because a BiFunction of this type would return an Integer, not an int. C is incorrect because accept is not the correct function name for an operator (it is the function name for a Consumer).

Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); System.out.println( ohMy.collect( Collectors.averagingInt(String::length) ) ); // What is the output? A. Code won't compile B. Compile but throw runtime exceptionC. C. The application hang forever D. Print the average length of the three animal names

D. We pass a collector to collect() and it performs the average for us. We needed to pass a function to tell the collector what to average. We used a method reference, which returns an int upon execution. With primitive streams, the result of an average was always a double , regardless of what type is being averaged. For collectors, it is a Double since those need an Object.

public class Market { private static void checkPrices(List<Double> prices, ____________scanner) { prices.forEach(scanner); } public static void main(String[] right) { List<Double> prices = Arrays.asList(1.2, 6.5, 3.0); checkPrices(prices, p -> { String result = p<5 ? "Correct" : "Too high"; System.out.println(result); }); } } // Which functional interface, when entered into the blank below, allows the class to compile? A. Consumer B. DoubleConsumer C. Supplier<Double> D. None of the above

D. First off, the forEach() method requires a Consumer instance. Option C can be immediately discarded because Supplier<Double> does not inherit Consumer. For this same reason, Option B is also incorrect. DoubleConsumer does not inherit from Consumer. In this manner, primitive functional interfaces cannot be used in the forEach() method. Option A seems correct, since forEach() does take a Consumer instance, but it is missing a generic argument. Without the generic argument, the lambda expression does not compile because the expression p<5 cannot be applied to an Object. The correct functional interface is Consumer<Double>, and since that is not available, Option D is the correct answer.

public class StreamOfStreams { public static void main(String[] args) { Integer result = Stream.of( getNums(9, 8), getNums(22, 33) ) // c1 .filter( x -> !x.isEmpty() ) // c2 .flatMap( x -> x ) // c3 .max( (a, b) -> a b ) // c4 .get(); System.out.println(result); } private static Stream<Integer> getNums(int num1, int num2) { return Stream.of(num1, num2); } } // What is the result? A. The code compiles and outputs 8. B. The code compiles and outputs 33. C. The code does not compile due to line c1. D. The code does not compile due to line c2. E. The code does not compile due to line c3. F. The code does not compile due to line c4.

D. Line c1 correctly creates a stream containing two streams. Line c2 does not compile since x is a stream, which does not have an isEmpty() method. Therefore, Option D is correct. If the filter() call was removed, flatMap() would correctly turn the stream into one with four Integer elements and max() would correctly find the largest one. The Optional returned would contain 33, so Option B would be the answer in that case.

Which statement about functional interfaces and lambda expressions is NOT true? A. A lambda expression may be compatible with multiple functional interfaces. B. A lambda expression must be assigned to a functional interface when it is declared. C. A method can return a lambda expression in the form of a functional interface instance. D. The compiler uses deferred execution to skip determining whether a lambda expression compiles or not.

D. Options A, B, and C are true statements about functional interfaces. A lambda may be compatible with multiple functional interfaces, but it must be assigned to a functional interface when it is declared or passed as a method argument. Also, a method can be created with the return type that matches a functional interface, allowing a lambda expression to be returned. Deferred execution means the lambda expression is not evaluated until runtime, but it is compiled. Compiler errors in the lambda expression will prevent the code from compiling.

Which lambda expression CANNOT be assigned to a DoubleToLongFunction functional interface? A. a -> null==null ? 1 : 2L B. e -> (int)(10.0*e) C. (double m) -> {long p = (long)m; return p;} D. (Double s) -> s.longValue()

D. The DoubleToLongFunction interface takes a double argument and returns a long value. Option A is compatible since the int value 1 can be implicitly cast to long, and 2L is already a long. Option B is also compatible, since the double value 10.0*e is explicitly cast to int then implicitly cast to long. Next, Option C is compatible because an explicit cast of the double to a long value is used. Option D cannot be assigned and is the correct answer. Although the Double class does have a longValue() method, the left-hand side of the lambda expression must use the primitive double, not the wrapper Double. Hence this lambda expression violates the signature of the functional interface, since it allows Double values to be sent to the interface, including those that could be null.

interface ApplyFilter { void filter(List<String> input); } public class FilterBobs { static Function<String,String> first = s ->{ System.out.println(s); return s; }; static Predicate second = t -> "bob".equalsIgnoreCase(t); public void process(ApplyFilter a, List<String> list) { a.filter(list); } public static void main(String[] contestants) { final List<String> people = Arrays.asList("Bob","bob","Jennifer","Samantha"); new FilterBobs().process( q -> { q.removeIf(second); q.forEach(first); }, people ); } } // What the output? A. It prints two lines. B. It prints three lines. C. One line of code does not compile. D. Two lines of code do not compile. E. Three lines of code do not compile. F. The code compiles but prints an exception at runtime.

D. The code does not compile, so Options A, B, and F are incorrect. The first compilation error is in the declaration of the lambda expression for second . It does not use a generic type, which means t is of type Object . Since Object , unlike String , does not have a method equalsIgnoreCase() , the lambda expression does not compile. The second compilation issue is in the lambda expression in the main() method. Notice that process() takes an ApplyFilter instance, and ApplyFilter is a functional interface that takes a List<String> object. For this reason, q in this lambda expression is treated as an instance of List<String> . The forEach() method defined in Collections requires a Consumer instance, not a Function , so the call q.forEach(first) does not compile. For these two reasons, Option D is the correct answer, since the rest of the code compiles without issue.

Set<String> set = new HashSet<>(); set.add("tire-"); List<String> list = new LinkedList<>(); Deque<String> queue = new ArrayDeque<>(); queue.push("wheel-"); Stream.of(set, list, queue) .flatMap(x -> x) .forEach(System.out::print); // What does the output? A. [tire-][wheel-] B. tire-wheel- C. None of the above D. The code does not compile.

D. The flatMap() method works with streams rather than collections. The code does not compile because the x is not a stream, making Option D correct. If this was fixed,Option B would be the answer.

Stream<String> s = Stream.of("over the river", "through the woods", "to grandmother's house we go"); s.filter(n -> n.startsWith("t")) .sorted(Comparator::reverseOrder) .findFirst() .ifPresent(System.out::println); // What is the output? A. over the river B. through the woods C. to grandmother's house we go D. None of the above

D. The sorted() method allows an optional Comparator to be passed as a reference. However, Comparator.reverseOrder() does not implement the Comparator interface. It takes zero parameters instead of the required two. Since it cannot be used as a method reference, the code does not compile, and Option D is correct

1:class Runner { 2: private int n; 3: public Runner(int n) { this.n = n; } 6: public int getNumberMinutes() { return n; } 9: public boolean isFourMinuteMile() { return n < 240; } } 15: Stream<Runner> runners = Stream.of( new Runner(250),new Runner(600), new Runner(201) ); 17: long count = runners 18: *.filter(Runner::isFourMinuteMile)* 19: .count(); // Which line can replace line 18 without changing the count value? A. .map(Runner::isFourMinuteMile) B. .mapToBool(Runner::isFourMinuteMile) .filter(b -> b == true) C. .mapToBoolean(Runner::isFourMinuteMile) .filter(b -> b == true) D. None of the above

D. There is no built-in method to map a value to a boolean primitive. Therefore,Options B and C don't even compile, so they are incorrect. Option A does compile as it maps a Runner to a Boolean. However, it doesn't actually filter() the stream to eliminate any values, so the output is not the same. It prints 3 instead of 1. None of these are correct, making Option D the answer.

4: public class FindMovie { 5: private Function<String> pr; 6: protected FindMovie() { 7: pr = s -> { System.out.println(s); return s; } 8: } 9: void printMovies(List<String> movies) { 10: movies.forEach(printer); 11: } 12: public static void main(String[] screen) { 13: List<String> movies = new ArrayList<>(); 14: movies.add("Stream 3"); 15: movies.add("Lord of the Recursion"); 16: movies.add("Silence of the Lambdas"); 17: new FindMovie().printMovies(movies); 18: } } // Given the following class, how many lines contain compilation errors? A. None. The code compiles as is. B. One C. Two D. Three

D. To start with, line 5 does not compile because Function takes two generic arguments, not one. Second, the assignment statement on line 7 does not end with a semicolon (;), so it also does not compile. Finally, the forEach() method on line 10 requires a Consumer, not a Function, so this line does not compile.

public class Sun { public static void dawn( *________* sunrise) {} public void main(String... rays) { dawn(s -> s+1); } } // Which functional interface, when filled into the blank, prevents the class from compiling? A. DoubleUnaryOperator B. Function<String,String> C. IntToLongFunction D. UnaryOperator

D. A lambda expression can match multiple functional interfaces. It matches DoubleUnaryOperator, which takes a double value and returns a double value. It also matches Function<String,String> since the (+) operator can be used for String concatenation. Finally, it matches IntToLongFunction since the int value s+1 can be implicitly cast to long. On the other hand, the lambda expression is not compatible with UnaryOperator without a generic type. When UnaryOperator is used without a generic argument, the type is assumed to be Object. Since the (+) operator is not defined on Object, the code does not compile due to the lambda expression body, making Option D the correct answer. Note that if the lambda expression did not rely on the (+) operator, such as s -> s, then UnaryOperator would be allowed by the compiler, even without a generic type.

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

E. Streams can be used only once. An exception that the "stream has already been operated upon or closed".

What is the output of the following? 4: public class Books { 5: public static void main(String[] args) { 6: IntStream pages = IntStream.of(200, 300); 7: long total = pages.sum(); 8: long count = pages.count(); 9: System.out.println(total + "-" + count); 10: } } A. 2-2 B. 200-1 C. 500-0 D. 500-2 E. The code does not compile. F. The code compiles but throws an exception at runtime

F. When summing int primitives, the return type is also an int. Since a long is larger, you can assign the result to it, so line 7 is correct. All the primitive stream types use long as the return type for count(). Therefore, the code compiles, and Option E is incorrect. When actually running the code, line 8 throws an IllegalStateException because the stream has already been used. Both sum() and count() are terminal operations and only one terminal operation is allowed on the same stream. Therefore, Option F is the answer.

Predicate ex = String::isEmpty; // Will compile?

No There is missing the generic for Predicate . This makes the parameter that was passed an Object rather than a String . The lambda expects a String.

Is the findFirst() reduction operation on the Stream?

No it does not look at each element in the stream (which reduction does).

IntStream stream = IntStream.empty(); System.out.println( stream.average() ); // output ?

OptionalDouble.empty Average() function returns double

E. IntStream.rangeClosed(10, 15) creates an IntStream of int primitives containing elements 10, 11, 12, 13, 14, and 15 (Observe that 15 is included). IntStream does not support the various collect methods supported by a regular Stream of objects. But it does support a boxed() method that returns a Stream<Integer> containing Integer objects.

Stream<Integer> values = IntStream.rangeClosed(10, 15).boxed(); //1 Object obj = values.collect(Collectors.partitioningBy(x-> x%2==0)); //2 System.out.println(obj); // What output? A. Compilation error at //1 B. Compilation error at //2 C. {[11, 13, 15], [10, 12, 14]} D. [[11, 13, 15], [10, 12, 14]] E. {false=[11, 13, 15], true=[10, 12, 14]}

BiPredicate<String, String> b1 = String::startsWith; System.out.println(b1.test("chicken", "chick")); ?

true

BinaryOperator<String> b1 = String::concat; System.out.println(b1.apply("baby ", "chick"));

baby chick

Stream<Character> chars = Stream.of( 'o', 'b', 's', 't', 'a', 'c', 'l', 'e'); // How to collect this stream to ArrayList (not just in List) ?

chars.collect( Collectors.toCollection( ArrayList::new ); )


Set pelajaran terkait

Shielded Metal Arc Welding Ch.11

View Set

XCEL Chapter 1: Basics of Principles of Insurance

View Set

Unit 8: Challenges of Population Growth and Migration

View Set

w14: identifying sites of infection, pathogens, and treatment

View Set

Disciplined Agile Scrum Master (DASM)

View Set