Streams API Questions with Answers

22 practice questions on Streams API (Core Java) with answers and step-by-step solutions. Try 10 samples below, then practise all 22 free in the AptiNest app.

Sample questions

Question 1Easy

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(Stream.iterate(1, n -> n * 3).skip(1).limit(3).collect(Collectors.toList()));
    }
}
  1. [3, 9, 27]
  2. [1, 3, 9, 27]
  3. [3, 9, 27, 81]
  4. [1, 3, 9]

Answer: A. [3, 9, 27]

Explanation

iterate yields 1, 3, 9, 27, ...; skip(1) drops 1 and limit(3) keeps the next three values.

Step-by-step solution

  1. Stream.iterate starts with 1 and generates 1, 3, 9, 27, ...
  2. skip(1) removes the first element, leaving 3, 9, 27, ...
  3. limit(3) takes the first three elements: 3, 9, 27.
  4. collect(Collectors.toList()) converts them to a list [3, 9, 27]
  5. Final answer: [3, 9, 27]

Why the other options are wrong

  • B. skip(1) removes the first element 1, so the output starts at 3.
  • C. limit(3) keeps only three elements, so 81 is cut off.
  • D. skip(1) drops the starting 1, so the three values are 3, 9, 27.

Tip: Remember that skip(1) removes the first element, and limit(3) takes the next three.

Question 2Easy

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(IntStream.range(1, 5).sum() + " " + IntStream.rangeClosed(1, 5).sum());
    }
}
  1. 15 15
  2. 15 10
  3. 10 10
  4. 10 15

Answer: D. 10 15

Explanation

range(1, 5) excludes 5 (1+2+3+4 = 10); rangeClosed(1, 5) includes it (15).

Step-by-step solution

  1. range(1, 5) includes 1 to 4, which sums to 10.
  2. rangeClosed(1, 5) includes 5, which sums to 15.
  3. The output is 10 15, which is option D.

Why the other options are wrong

  • A. Range excludes the upper bound 5, so the first sum is 10, not 15.
  • B. The first sum is 10 and the second is 15, so 15 10 is reversed.
  • C. RangeClosed includes 5, so the second sum is 15, not 10.

Tip: Range excludes the end value; rangeClosed includes it.

Question 3Easy

Which of these Stream operations is a terminal operation?

  1. sorted()
  2. map()
  3. filter()
  4. collect()

Answer: D. collect()

Explanation

collect() produces a result and ends the pipeline; map, filter and sorted are lazy intermediate operations that return a new Stream.

Step-by-step solution

  1. Sorted, map and filter are lazy intermediate operations that return a new Stream.
  2. Collect produces a final result and ends the pipeline.
  3. So the terminal operation is collect(), which is option D.

Why the other options are wrong

  • A. sorted() returns a new Stream, so it is intermediate.
  • B. map() returns a new Stream, so it is intermediate.
  • C. filter() returns a new Stream, so it is intermediate.

Tip: A terminal operation such as collect, count or forEach ends the stream pipeline.

Question 4Easy

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> r = Stream.of(1, 2, 3, 4, 5, 6)
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .collect(Collectors.toList());
        System.out.println(r);
    }
}
  1. [4, 16, 36]
  2. [2, 4, 6]
  3. [4, 16]
  4. [1, 9, 25]

Answer: A. [4, 16, 36]

Explanation

filter keeps 2, 4, 6 and map squares them, preserving encounter order.

Step-by-step solution

  1. filter(n -> n % 2 == 0) keeps 2, 4, 6.
  2. map(n -> n * n) squares each to get 4, 16, 36.
  3. collect(Collectors.toList()) stores them in list r.
  4. System.out.println(r) prints [4, 16, 36].
  5. Final answer is [4, 16, 36].

Why the other options are wrong

  • B. The map step squares each value, so 2, 4, 6 become 4, 16, 36 and are not printed unchanged.
  • C. The filter keeps 6 too, so 36 is also in the list.
  • D. Those are squares of odd numbers, but filter keeps even numbers 2, 4, 6.

Tip: Remember that stream operations are performed in order: filter first, then map.

Question 5Medium

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        OptionalDouble avg = IntStream.of(2, 3, 4, 6).average();
        OptionalDouble none = IntStream.empty().average();
        System.out.println(avg.getAsDouble() + " " + none.isPresent());
    }
}
  1. 3.0 false
  2. 3.75 true
  3. 3 false
  4. 3.75 false

Answer: D. 3.75 false

Explanation

average() returns an OptionalDouble: (2+3+4+6)/4 = 3.75; for an empty stream there is no average, so isPresent() is false.

Step-by-step solution

  1. average() returns an OptionalDouble for the values 2, 3, 4 and 6.
  2. The sum is 15 and the count is 4, so the average is 15 divided by 4, which is 3.75.
  3. An empty stream has no average, so isPresent() is false.
  4. The output is 3.75 false, which is option D.

Why the other options are wrong

  • A. The average is 3.75, not 3.0, because the sum is 15 divided by 4.
  • B. An empty stream has no average, so isPresent() is false, not true.
  • C. The average keeps the decimal part, so it is 3.75, not 3.

Tip: Average on an int stream returns an OptionalDouble, so check isPresent for empty streams.

Question 6Medium

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<String> r = Stream.of("pear", "fig", "kiwi", "apple", "date")
            .sorted(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()))
            .collect(Collectors.toList());
        System.out.println(r);
    }
}
  1. [fig, date, kiwi, pear, apple]
  2. [apple, date, fig, kiwi, pear]
  3. [fig, pear, kiwi, date, apple]
  4. [fig, kiwi, pear, date, apple]

Answer: C. [fig, pear, kiwi, date, apple]

Explanation

Strings are ordered by length first; ties of length 4 (pear, kiwi, date) are broken in reverse alphabetical order: pear, kiwi, date.

Step-by-step solution

  1. Words are sorted by length first: fig (3), then the length 4 words, then apple (5).
  2. The length 4 ties are pear, kiwi and date, sorted by reverse alphabetical order.
  3. Reverse alphabetical order gives pear, kiwi, date.
  4. The result is fig, pear, kiwi, date, apple, which is option C.

Why the other options are wrong

  • A. Length 4 ties are not in reverse order; date comes before pear here.
  • B. Apple is the longest word, so it must be last, not first.
  • D. In reverse order pear comes before kiwi, so kiwi before pear is wrong.

Tip: ThenComparing breaks ties left by the first comparator.

Question 7Medium

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        int r = Stream.of(1, 2, 3, 4).reduce(10, (a, b) -> a + b);
        Optional<Integer> m = Stream.of(5, 3, 8).reduce(Integer::max);
        System.out.println(r + " " + m.get());
    }
}
  1. 20 5
  2. 10 8
  3. 20 8
  4. 30 8

Answer: C. 20 8

Explanation

reduce with identity 10 adds 1 + 2 + 3 + 4 to give 20; reduce without an identity returns an Optional, here holding the max 8.

Step-by-step solution

  1. Stream.of(1, 2, 3, 4).reduce(10, (a, b) -> a + b) adds 1 + 2 + 3 + 4 to 10 giving 20.
  2. Stream.of(5, 3, 8).reduce(Integer::max) finds the max of 5, 3, 8 which is 8.
  3. r = 20 and m.get() = 8 so output is 20 8.
  4. Final answer: 20 8.

Why the other options are wrong

  • A. The max of 5, 3, 8 is 8, not 5; reduce(Integer::max) returns the largest value.
  • B. reduce with identity 10 adds 1+2+3+4 to 10, giving 20, not 10.
  • D. The sum of 1+2+3+4 is 10; adding it to identity 10 gives 20, not 30.

Tip: Remember that reduce with an initial value adds elements to it, while without it returns an Optional with the final result.

Question 8Medium

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Map<Character, Integer> m = Stream.of("apple", "avocado", "banana")
            .collect(Collectors.toMap(s -> s.charAt(0), String::length, Integer::sum, TreeMap::new));
        System.out.println(m);
    }
}
  1. {a=12, b=6}
  2. {a=7, b=6}
  3. IllegalStateException
  4. {a=5, b=6}

Answer: A. {a=12, b=6}

Explanation

The merge function Integer::sum combines the lengths of apple (5) and avocado (7) into 12; TreeMap::new keeps keys sorted.

Step-by-step solution

  1. Stream.of creates a stream of strings: 'apple', 'avocado', 'banana'.
  2. S -> s.charAt(0) maps each string to its first character: 'a', 'a', 'b'.
  3. String::length gives lengths: 5, 7, 6. Integer::sum adds same keys: 5 + 7 = 12.
  4. TreeMap::new sorts keys: a comes before b. Final map is {a=12, b=6}.
  5. System.out.println prints the map as {a=12, b=6}.

Why the other options are wrong

  • B. apple and avocado both start with a, so their lengths 5 and 7 are merged into 12, not kept apart.
  • C. toMap throws only on duplicate keys without a merge function; here Integer::sum merges them.
  • D. The merge function adds 5 and 7 for key a, so a is 12, not just the first length 5.

Tip: Use Integer::sum for adding lengths of same first letters in strings.

Question 9Hard

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Stream.of("x", "y", "z")
                .peek(s -> System.out.print("p" + s + " "))
                .map(String::toUpperCase)
                .forEach(s -> System.out.print(s + " "));
        System.out.println();
    }
}
  1. X Y Z px py pz
  2. px X
  3. px X py Y pz Z
  4. px py pz X Y Z

Answer: C. px X py Y pz Z

Explanation

Streams process elements one at a time through the whole pipeline (vertical processing), not stage by stage.

Step-by-step solution

  1. Streams process one element at a time through the whole pipeline.
  2. For x: peek prints px, then map and forEach print X.
  3. The same pattern runs for y and z.
  4. The output is px X py Y pz Z, which is option C.

Why the other options are wrong

  • A. Elements are not processed stage by stage, so peek does not print all three first.
  • B. All three elements are processed, so the output has all six items.
  • D. Each element goes through the pipeline in turn, so px is followed by X before py.

Tip: Stream stages run per element, not stage by stage.

Question 10Hard

What is the output?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> r = Stream.of(1, 3, 5, 6, 7, 9)
            .takeWhile(n -> n % 2 == 1)
            .collect(Collectors.toList());
        List<Integer> s = Stream.of(1, 3, 5, 6, 7, 9)
            .dropWhile(n -> n % 2 == 1)
            .collect(Collectors.toList());
        System.out.println(r + " " + s);
    }
}
  1. [1, 3, 5] [6, 7, 9]
  2. [1, 3, 5, 7, 9] [6, 7, 9]
  3. [1, 3, 5] [6]
  4. [1, 3, 5, 7, 9] [6]

Answer: A. [1, 3, 5] [6, 7, 9]

Explanation

takeWhile stops at the first element failing the predicate (6); dropWhile skips only the leading matching run and keeps everything from 6 onward, including 7 and 9.

Step-by-step solution

  1. TakeWhile keeps elements from the start while the test is true: 1, 3, 5, then stops at 6.
  2. DropWhile skips only the leading run of matches: 1, 3, 5 are dropped.
  3. DropWhile keeps everything from 6 onward: 6, 7, 9.
  4. The output is [1, 3, 5] [6, 7, 9], which is option A.

Why the other options are wrong

  • B. TakeWhile stops at 6, so 7 and 9 are not included.
  • C. DropWhile keeps 7 and 9 as well, so the second list is not just 6.
  • D. TakeWhile stops at 6, and dropWhile does not drop 7 or 9.

Tip: TakeWhile stops at the first failure; dropWhile skips only the leading matches and keeps the rest.

Practise all 22 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Core Java topics · All topics