Stream API practice questions

From OCP Java SE 8 (1Z0-809) · 25 questions on this topic

Stream API practice questions from OCP Java SE 8 (1Z0-809). This pack has 25 questions tagged Stream API, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Stream API

  1. Question 1

    What is the output of the following program? ```java import java.util.stream.Stream; public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); Stream.of(1, 2, 3) .peek(sb::append) .filter(n -> n % 2 == 1) .forEach(n -> { }); System.out.println(sb); } } ```

    1. A. An empty line

      The forEach terminal forces the pipeline to execute, so output is produced.

    2. B. Compilation fails

      The pipeline is well formed and compiles.

    3. C. 13

      This is what peek would record if placed after the filter; before it, every element is seen.

    4. D. 123Correct answer

      Correct: peek runs before filtering, so it captures all three elements in order.

    Explanation

    peek observes every element that flows through it at its position in the pipeline, and here it sits before the filter, so it sees all elements even those later discarded. A terminal operation drives the pipeline to run.

  2. Question 2

    What is the output of the following program? ```java import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { List<Integer> l = Stream.of(3, 1, 2) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); System.out.println(l); } } ```

    1. A. [3, 2, 1]Correct answer

      Correct: the reverse comparator sorts the values from largest to smallest.

    2. B. Compilation fails

      The pipeline is well typed and compiles.

    3. C. [1, 2, 3]

      This is ascending order, which the natural no-argument sort would give, not the reverse comparator.

    4. D. [3, 1, 2]

      This is the unsorted input; the sort does reorder the elements.

    Explanation

    Sorting with a reverse-order comparator arranges the elements in descending order. The collected list reflects that ordering.

  3. Question 3

    What is the output of the following program? ```java import java.util.stream.IntStream; public class Main { public static void main(String[] args) { System.out.println(IntStream.rangeClosed(1, 4).sum() + " " + IntStream.range(1, 4).max().getAsInt()); } } ```

    1. A. 10 3Correct answer

      rangeClosed(1, 4) includes 4 so its sum is 1+2+3+4 = 10, while range(1, 4) excludes 4 leaving max 3.

    2. B. 6 4

      This treats rangeClosed as excluding 4 (giving 6) and range as including it (giving max 4), reversing which method is inclusive of the upper bound.

    3. C. 10 4

      The sum of 10 is right, but this wrongly treats range as inclusive of 4; range excludes its upper bound, so its max is 3.

    4. D. 6 3

      The max of 3 is right, but this wrongly treats rangeClosed as excluding 4; rangeClosed includes it, so the sum is 10, not 6.

    Explanation

    rangeClosed includes the upper bound: 1+2+3+4 = 10. range EXCLUDES it: 1,2,3 with max 3. The Closed suffix is the entire difference — and max() returns an OptionalInt, unwrapped with getAsInt.

  4. Question 4

    What is the output of the following program? ```java import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { try { Map<Integer, String> m = Stream.of("aa", "bb", "c") .collect(Collectors.toMap(String::length, s -> s)); System.out.println(m); } catch (IllegalStateException e) { System.out.println("dup"); } } } ```

    1. A. {1=c, 2=bb}

      This assumes a last-wins merge, but the two-argument toMap has no merge function and throws on a key collision rather than keeping the later value.

    2. B. Compilation fails

      toMap with a key mapper and a value mapper is a valid two-argument call that compiles; the failure is a runtime exception, not a compile error.

    3. C. {1=c, 2=aa}

      This assumes a first-wins merge, which again requires the three-argument toMap; the two-argument form does not silently keep either colliding value.

    4. D. dupCorrect answer

      "aa" and "bb" both produce key 2, and the two-argument toMap has no merge policy, so it throws IllegalStateException, which the catch block reports as "dup".

    Explanation

    The two-argument Collectors.toMap has no merge function, so when two elements produce the same key it throws IllegalStateException rather than choosing a winner. Both two-letter strings map to the same length key, triggering that collision, which the surrounding catch converts into its printed message.

  5. Question 5

    What is the output of the following program? ```java import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { Map<Integer, Long> m = Stream.of("x", "yy", "zz") .collect(Collectors.groupingBy( String::length, TreeMap::new, Collectors.counting())); System.out.println(m); } } ```

    1. A. Compilation fails

      The three-argument groupingBy with a map factory and downstream collector is valid and compiles.

    2. B. {1=1, 2=2} in unpredictable key order

      The TreeMap factory guarantees sorted, predictable key order rather than an arbitrary one.

    3. C. {1=[x], 2=[yy, zz]}

      counting produces group sizes, not the lists of members the default collector would give.

    4. D. {1=1, 2=2}Correct answer

      Correct: each length group is counted, and the TreeMap sorts the keys.

    Explanation

    A downstream counting collector replaces the default list, so each group's value is its size. Supplying a TreeMap factory makes the key order sorted and deterministic.

  6. Question 6

    What is the output of the following program? ```java import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { Map<Integer, List<String>> m = Stream.of("ant", "bee", "wasp", "fly") .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList())); System.out.println(m); } } ```

    1. A. {3=[ant, bee], 4=[wasp, fly]}

      This miscounts fly as four letters; fly has three letters and belongs in the length-3 bucket, not with wasp.

    2. B. Compilation fails

      groupingBy with a classifier, a map supplier, and a downstream collector is a valid three-argument overload, so the code compiles.

    3. C. {4=[wasp], 3=[ant, bee, fly]}

      The grouping is right, but the TreeMap supplier sorts keys ascending, so 3 must appear before 4.

    4. D. {3=[ant, bee, fly], 4=[wasp]}Correct answer

      Elements group by string length with ant, bee, and fly (all three letters) under key 3 and wasp under key 4, and the TreeMap orders the keys ascending.

    Explanation

    groupingBy partitions elements into buckets keyed by the classifier's result, preserving encounter order within each bucket. Grouping by length places the three-letter words together and the four-letter word alone, and the supplied TreeMap presents the keys in ascending order.

  7. Question 7

    What is the output of the following program? ```java import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { Map<Boolean, List<Integer>> m = Stream.of(1, 2, 3) .collect(Collectors.partitioningBy(n -> n > 5)); System.out.println(m); } } ```

    1. A. {true=[], false=[1, 2, 3]}

      Both keys are present, but the partition map orders the false key before the true key, not the reverse.

    2. B. {false=[1, 2, 3], true=[]}Correct answer

      None of 1, 2, 3 exceed 5, so all fall in the false bucket, and partitioningBy still includes an empty true bucket, with false ordered first.

    3. C. {}

      partitioningBy never returns an empty map; it always contains both the false and true entries.

    4. D. {false=[1, 2, 3]}

      This omits the empty true bucket, which is how groupingBy would behave; partitioningBy always keeps both keys.

    Explanation

    partitioningBy always yields a map with both the false and true keys, inserting an empty list for a side that matches nothing. Since none of the values satisfy the predicate, they all land under false while true maps to an empty list, with false ordered first.

  8. Question 8

    What is the output of the following program? ```java import java.util.stream.Stream; public class Main { public static void main(String[] args) { long n = Stream.of("a", "bb", "ccc") .filter(s -> s.length() > 1) .map(String::toUpperCase) .count(); System.out.println(n); } } ```

    1. A. 1

      Both multi-character strings pass the length filter, so two elements remain, not one.

    2. B. Compilation fails

      The filter, map, and count pipeline is well typed and compiles.

    3. C. 3

      The single-character element is removed by the length filter, leaving fewer than all three.

    4. D. 2Correct answer

      Correct: the filter keeps the two multi-character strings, and map transforms them without changing the count.

    Explanation

    filter keeps bb and ccc (length > 1); map transforms but never changes the COUNT. Two elements reach the terminal: 2.

Practise all 25 Stream API questions

OCP Java SE 8 has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open OCP Java SE 8

Other topics in this pack