THINK FIRST·CODE LATER

← Data Structures and Algorithms
Chapter 3 · Week 2–3

Lambdas, Comparators and Streams

Answered 0/33 Correct 0
Sign in to save progress across devices
Q1

Which declaration compiles?

Q2

Which pairing of a functional interface with its single abstract method is wrong?

Q3

What is the result of compiling and running this fragment?

int limit = 3;
Predicate<String> longer = s -> s.length() > limit;
limit = 4;
System.out.println(longer.test("tree"));
Q4

Assuming a suitable functional-interface target type, which lambda is not legal syntax?

Q5

Which method reference can replace the lambda in Function<String, String> f = s -> s.toUpperCase();?

Q6

Which of these is an unbound instance method reference?

Q7

What does this fragment print?

BiFunction<String, Integer, Character> f = String::charAt;
Function<String, StringBuilder> make = StringBuilder::new;
System.out.println(f.apply("lambda", 2) + "" + make.apply("ab").reverse());
Q8

What does this fragment print?

List<String> words = Arrays.asList("stack", "queue", "tree", "graph", "heap");
List<String> r = words.stream()
        .filter(w -> w.length() == 5)
        .map(w -> w.substring(0, 2))
        .collect(Collectors.toList());
System.out.println(r);
Q9

What does this fragment print?

Stream<Integer> s = Stream.of(1, 2, 3).map(x -> {
    System.out.print(x);
    return x * 2;
});
System.out.println("done");
Q10

What is the result?

Stream<String> s = Stream.of("a", "b", "c");
System.out.println(s.count());
System.out.println(s.count());
Q11

You want list.sort(c) to put the longest strings first. Which c works?

Q12

What does this fragment print?

List<String> list = new ArrayList<>(Arrays.asList("pear", "fig", "apple", "kiwi", "date"));
list.sort(Comparator.comparing(String::length)
                    .thenComparing(Comparator.reverseOrder()));
System.out.println(list);
Q13

Which statement about Comparable and Comparator is true?

Q14

Given the class below, what happens with the fragment that follows?

class Box {
    int weight;
    Box(int weight) { this.weight = weight; }
}
// ... in main:
List<Box> boxes = new ArrayList<>();
boxes.add(new Box(5));
boxes.add(new Box(2));
Collections.sort(boxes);
Q15

What does this fragment print?

List<Integer> nums = new ArrayList<>(Arrays.asList(5, 12, 8, 3, 20));
boolean changed = nums.removeIf(n -> n % 4 == 0);
System.out.println(changed + " " + nums);
Q16

Does this line compile?

int n = Stream.of("x", "y", "z").filter(s -> !s.equals("y")).count();
Q17

What does this fragment print?

int r = Stream.of(1, 2, 3, 4).reduce(10, (a, b) -> a + b);
System.out.println(r);
Q18

What does this fragment print?

List<String> w = Arrays.asList("ant", "bee", "cat", "dove", "eel", "frog");
Map<Integer, Long> m = w.stream()
        .collect(Collectors.groupingBy(String::length, Collectors.counting()));
System.out.println(m.get(3) + " " + m.get(4) + " " + m.get(5));
Q19

What does this fragment print?

String s = Stream.of("b", "a", "c", "a")
        .distinct()
        .sorted()
        .collect(Collectors.joining("-", "<", ">"));
System.out.println(s);
Q20

What is the declared return type of IntStream.of(2, 4, 7).average()?

Q21

What does this fragment print?

List<String> empty = new ArrayList<>();
String a = empty.stream().max(Comparator.naturalOrder()).orElse("none");
Optional<String> b = Stream.of("kiwi", "fig", "banana", "melon")
        .max(Comparator.comparing(String::length));
System.out.println(a + " " + b.get());
Q22

What does this fragment print?

Stream.of(5, 3, 5, 1, 3, 8, 1)
      .distinct()
      .sorted()
      .limit(3)
      .forEach(x -> System.out.print(x + " "));
Q23

What does this fragment print?

Stream.of("a", "bb", "ccc")
      .filter(s -> { System.out.print("F" + s + " "); return s.length() > 1; })
      .map(s -> { System.out.print("M" + s + " "); return s.toUpperCase(); })
      .forEach(s -> System.out.print(s + " "));
Q24

What does this fragment print?

List<Integer> nums = new ArrayList<>(Arrays.asList(4, 9, 1, 7));
Comparator<Integer> c = (a, b) -> b - a;
nums.sort(c.reversed());
System.out.println(nums);
Q25

What does this fragment print?

Function<Integer, Integer> add3 = x -> x + 3;
Function<Integer, Integer> times2 = x -> x * 2;
System.out.println(add3.andThen(times2).apply(4) + " " + add3.compose(times2).apply(4));
Q26

Using the Box class of question 14 (no Comparable), what happens here?

List<Box> sorted = Stream.of(new Box(5), new Box(2))
        .sorted()
        .collect(Collectors.toList());
System.out.println(sorted.size());
Q27

Which statement compiles and sorts List<String> names from longest to shortest?

Q28 Short answer

Explain what it means that intermediate stream operations are lazy. Give a short pipeline where laziness means that fewer elements are processed than the source contains, and say how many are processed.

Q29 Short answer

String already implements Comparable<String>. Give two different situations in which you would still write a Comparator<String>, and show the comparator for each.

Q30 Short answer

A student writes the code below to count how many words are longer than 4 characters. Explain why it does not compile, and rewrite it correctly with a stream.

int count = 0;
words.forEach(w -> { if (w.length() > 4) count++; });
Q31 Short answer

Name the four kinds of method reference. For each, give an example and the equivalent lambda.

Q32 Programming

Write a method

static List<String> shortlist(List<String> names, int k)

that returns at most k distinct names that start with an upper-case letter, ordered by length (shortest first) and, for equal lengths, alphabetically. Use a single stream pipeline. Ignore empty strings. For example, ["Zoe", "al", "Bea", "Omar", "Zoe", "Ian"] with k = 3 gives [Bea, Ian, Zoe].

Q33 Programming

Write a method

static Map<Character, Long> countByInitial(List<String> words)

that counts the words by their first letter, ignoring case, and returns the map with its keys in alphabetical order. Skip empty strings. For ["Apple", "avocado", "banana", "Cherry", "", "cranberry"] the result prints as {a=2, b=1, c=2}.