Unit 1: Collections, Streams, Filters, and Lambdas - Practice Quiz

CSE406 — Advanced Java Programming 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the main purpose of the Builder pattern in Java?

Describing the Builder pattern Easy
A. To sort objects automatically
B. To execute methods in parallel
C. To convert objects into streams
D. To construct complex objects step by step

2 Which statement prints every element of a list named names using lambda syntax?

Iterating through a collection using lambda syntax Easy
A. names.filter(name -> System.out.println(name));
B. names.map(name -> System.out.println(name));
C. names.forEach(name -> System.out.println(name));
D. names.collect(name -> System.out.println(name));

3 What does a Java stream primarily represent?

Describing the Stream interface Easy
A. A container that permanently stores elements
B. A thread that executes background operations
C. A sequence of elements supporting aggregate operations
D. A file that contains serialized elements

4 Which stream operation selects only the elements that satisfy a lambda condition?

Filtering a collection using lambda expressions Easy
A. sorted
B. map
C. reduce
D. filter

5 What does numbers.stream().filter(n -> n > 10) produce?

Filtering a collection using lambda expressions Easy
A. A stream containing numbers less than 10
B. A count of numbers greater than 10
C. A stream containing numbers greater than 10
D. A sum of numbers greater than 10

6 What does method chaining mean in a Java stream pipeline?

Chaining multiple methods together Easy
A. Storing multiple streams in one variable
B. Calling multiple operations one after another
C. Calling one operation from several threads
D. Defining multiple classes in one file

7 Which sequence correctly describes a basic stream pipeline?

Defining pipelines in terms of lambdas and collections Easy
A. Source, terminal operation, intermediate operations
B. Source, intermediate operations, terminal operation
C. Intermediate operations, terminal operation, source
D. Terminal operation, source, intermediate operations

8 Which collection method directly creates a parallel stream?

Describing how to make a stream pipeline execute in parallel Easy
A. parallel()
B. parallelStream()
C. parallelize()
D. streamParallel()

9 What is reduction in the Java Stream API?

Defining reduction Easy
A. Combining stream elements into one result
B. Dividing a stream into several lists
C. Removing duplicate elements from a stream
D. Converting each element into another type

10 What is the result of Stream.of(1, 2, 3).reduce(0, (a, b) -> a + b)?

Calculating a value using reduce Easy
A. 3
B. 0
C. 6
D. 5

11 In parallel stream processing, what happens after work is divided into smaller tasks?

Describing the process for decomposing and then merging work Easy
A. The original collection is deleted
B. The intermediate results are ignored
C. The tasks become sequential streams
D. The partial results are combined

12 Given a stream of Person objects, which operation extracts each person's name?

Extracting data from an object using map Easy
A. .reduce(person -> person.getName())
B. .sorted(person -> person.getName())
C. .filter(person -> person.getName())
D. .map(person -> person.getName())

13 Which of the following is an intermediate stream operation?

Describing the types of stream operations Easy
A. count
B. collect
C. forEach
D. map

14 Which of the following is a terminal stream operation?

Describing the types of stream operations Easy
A. filter
B. sorted
C. distinct
D. collect

15 Why is the Optional class commonly used?

Describing the Optional class Easy
A. To represent a value that may be absent
B. To arrange values in sorted order
C. To execute an operation in parallel
D. To represent a collection that is immutable

16 When are intermediate stream operations normally executed?

Describing lazy processing Easy
A. When the stream variable is declared
B. When the collection is first created
C. When the lambda expression is compiled
D. When a terminal operation is invoked

17 Which operation sorts stream elements according to their natural order?

Sorting a stream Easy
A. sorted()
B. compared()
C. arranged()
D. ordered()

18 Which expression saves stream elements into a List?

Saving results to a collection using the collect method Easy
A. .collect(Collectors.toList())
B. .map(Collectors.toList())
C. .collect(Collectors.toSet())
D. .reduce(Collectors.toList())

19 Which collector divides elements into two groups based on a predicate?

Grouping and partitioning data using the Collectors class Easy
A. Collectors.groupingBy(...)
B. Collectors.partitioningBy(...)
C. Collectors.mapping(...)
D. Collectors.joining(...)

20 Which lambda expression correctly represents an operation that multiplies an integer x by 2?

Program to implement Lambda operations Easy
A. x -> x * 2
B. x <- x * 2
C. x => x * 2
D. x :: x * 2

21 Which situation most strongly justifies using the Builder pattern in Java?

Describing the Builder pattern Medium
A. An object has many optional configuration fields
B. An object must contain only static methods
C. An object requires one fixed constructor argument
D. An object is created exclusively through inheritance

22 What is printed by the following code?

JAVA
List<String> names = Arrays.asList("Ana", "Bob", "Cara");
names.forEach(name -> System.out.print(name + " "));

Iterating through a collection using lambda syntax Medium
A. Ana Bob Cara
B. Ana, Bob, Cara
C. The list object reference
D. name name name

23 Which statement correctly describes a Java Stream?

Describing the Stream interface Medium
A. It represents a sequence for processing data
B. It replaces all collection implementations
C. It permanently stores transformed collection elements
D. It guarantees that every operation runs concurrently

24 Which expression creates a stream containing only positive integers from numbers?

Filtering a collection using lambda expressions Medium
A. numbers.stream().reduce(n -> n > 0)
B. numbers.stream().filter(n -> n > 0)
C. numbers.stream().map(n -> n > 0)
D. numbers.stream().collect(n -> n > 0)

25 What is the result of this pipeline?

JAVA
List<String> result = words.stream()
    .filter(w -> w.length() > 3)
    .map(String::toUpperCase)
    .sorted()
    .toList();

Chaining multiple methods together Medium
A. Words shorter than three characters, sorted
B. Only the first matching word, converted to uppercase
C. Uppercase words longer than three characters, sorted
D. All words converted to uppercase, in original order

26 In a stream pipeline, which operation normally represents the terminal operation?

Defining pipelines in terms of lambdas and collections Medium
A. The operation that creates the source stream
B. The operation that declares the collection type
C. The operation that selects a lambda parameter
D. The operation that produces a final result

27 Which code converts a collection into a parallel stream pipeline?

Describing how to make a stream pipeline execute in parallel Medium
A. items.parallel().map(this::process).toList()
B. items.stream().parallelize(this::process).toList()
C. items.stream().concurrent(this::process).toList()
D. items.parallelStream().map(this::process).toList()

28 What is the purpose of a reduction operation on a stream?

Defining reduction Medium
A. To reorder elements without combining them
B. To divide each element into smaller objects
C. To preserve every intermediate stream
D. To combine elements into one summary result

29 What value is assigned to total?

JAVA
int total = Stream.of(2, 4, 6)
    .reduce(1, (a, b) -> a + b);

Calculating a value using reduce Medium
A. 11
B. 13
C. 7
D. 12

30 Which description best matches fork/join processing used by parallel streams?

Describing the process for decomposing and then merging work Medium
A. Copy the source into every worker without merging
B. Run one task repeatedly until the source is empty
C. Execute only the first subtask and discard the rest
D. Split work into subtasks, then combine their results

31 Which expression produces a stream of email addresses from a stream of Customer objects?

Extracting data from an object using map Medium
A. customers.sorted(Customer::getEmail)
B. customers.filter(Customer::getEmail)
C. customers.reduce(Customer::getEmail)
D. customers.map(Customer::getEmail)

32 Which classification is correct for filter, map, and count?

Describing the types of stream operations Medium
A. All three operations are terminal
B. Map and count are intermediate; filter is terminal
C. Filter and count are intermediate; map is terminal
D. Filter and map are intermediate; count is terminal

33 Why might a method return Optional<String> instead of returning String directly?

Describing the Optional class Medium
A. To guarantee that the string is never empty
B. To represent a value that may be absent
C. To make all string operations immutable
D. To convert the string into a parallel stream

34 When are intermediate stream operations such as filter and map generally executed?

Describing lazy processing Medium
A. Only after the stream variable is discarded
B. When a terminal operation consumes the stream
C. Before the stream source is created
D. Immediately when each method is declared

35 Which pipeline sorts integers in descending order and collects them into a list?

Sorting a stream Medium
A. values.stream().sorted(Comparator.reverseOrder()).toList()
B. values.stream().sort(Comparator.reverseOrder()).toList()
C. values.stream().reverse(Comparator.reverseOrder()).toList()
D. values.stream().ordered(Comparator.reverseOrder()).toList()

36 Which statement collects the names with length at least five into a mutable ArrayList?

Saving results to a collection using the collect method Medium
A. names.stream().filter(n -> n.length() >= 5).toArray(ArrayList::new)
B. names.stream().filter(n -> n.length() >= 5).reduce(new ArrayList<>(), ArrayList::add)
C. names.stream().filter(n -> n.length() >= 5).collect(Collectors.toList())
D. names.stream().filter(n -> n.length() >= 5).collect(Collectors.toCollection(ArrayList::new))

37 What does the following collector produce?

JAVA
Map<Boolean, List<Integer>> groups = numbers.stream()
    .collect(Collectors.partitioningBy(n -> n % 2 == 0));

Grouping and partitioning data using the Collectors class Medium
A. Lists grouped by each distinct numeric value
B. Two lists keyed by whether numbers are even
C. A single list sorted by the parity of numbers
D. A map containing only the even numbers

38 Which collector groups employees by their department name?

Grouping and partitioning data using the Collectors class Medium
A. Collectors.joining(Employee::getDepartment)
B. Collectors.partitioningBy(Employee::getDepartment)
C. Collectors.groupingBy(Employee::getDepartment)
D. Collectors.mapping(Employee::getDepartment)

39 Which lambda correctly represents a Predicate<Integer> that accepts even numbers?

Program to implement Lambda operations Medium
A. n -> n + 2
B. n -> System.out.println(n)
C. n -> n % 2 == 0
D. n -> Integer.valueOf(n)

40 Which pipeline calculates the average length of non-blank strings while avoiding an exception when no strings match?

Defining pipelines in terms of lambdas and collections Medium
A. words.stream().mapToInt(String::length).filter(s -> !s.isBlank()).average()
B. words.stream().filter(s -> !s.isBlank()).mapToInt(String::length).average()
C. words.stream().filter(s -> !s.isBlank()).map(String::length).sum()
D. words.stream().reduce(0, (a, s) -> a + s.length()).average()

41 An immutable Report stores a List<String> supplied through its builder. Which implementation best prevents both the caller and the builder from changing the constructed report's list?

Describing the Builder pattern Hard
A. Copy the list in the builder setter but store the builder's copy directly
B. Store builder.items directly and return a new list from the getter
C. Store builder.items directly and return it through an unmodifiable view
D. Copy the list in the Report constructor using List.copyOf(builder.items)

42 Assume result is a thread-safe list. What is guaranteed after executing List.of(1, 2, 3, 4).parallelStream().forEach(result::add)?

Iterating through a collection using lambda syntax Hard
A. result may omit values because forEach is non-deterministic
B. result must contain the values in reverse encounter order
C. result contains all four values exactly once in encounter order
D. result contains all four values exactly once, but their order is unspecified

43 What happens when the following code is executed?

Stream<Integer> s = Stream.of(1, 2, 3);

long count = s.count();

Optional<Integer> first = s.findFirst();

Describing the Stream interface Hard
A. findFirst() throws NoSuchElementException because no elements remain
B. findFirst() returns Optional.of(1) because streams can execute repeatedly
C. findFirst() throws IllegalStateException because the stream was already consumed
D. findFirst() returns Optional.empty() because count() exhausted the elements

44 For a list containing the integers 1 through 8, consider:

AtomicInteger gate = new AtomicInteger();

List<Integer> r = values.parallelStream().filter(x -> gate.getAndIncrement() % 2 == 0).toList();

Which statement is correct?

Filtering a collection using lambda expressions Hard
A. r always contains [2, 4, 6, 8] because increments occur before testing
B. r has four elements, but which values pass may vary between executions
C. r always contains [1, 3, 5, 7] because the source is ordered
D. r may have any size because a parallel filter can invoke predicates repeatedly

45 What list is produced by the following pipeline?

Stream.of(5, 3, 3, 2, 4, 2, 1).filter(n -> n % 2 != 0).distinct().sorted().skip(1).limit(1).toList()

Chaining multiple methods together Hard
A. [5]
B. [3]
C. [1]
D. [3, 5]

46 After this code finishes, what are the values of sum and mapped.get()?

AtomicInteger mapped = new AtomicInteger();

int sum = IntStream.iterate(1, n -> n + 1).filter(n -> n % 2 == 0).map(n -> { mapped.incrementAndGet(); return n * n; }).limit(3).sum();

Defining pipelines in terms of lambdas and collections Hard
A. sum is 56 and mapped.get() is 6
B. sum is 20 and mapped.get() is 6
C. sum is 20 and mapped.get() is 3
D. sum is 56 and mapped.get() is 3

47 For List<Integer> values = List.of(9, 2, 8, 4, 6);, which result is guaranteed by values.parallelStream().filter(n -> n % 2 == 0).findFirst()?

Describing how to make a stream pipeline execute in parallel Hard
A. Any even value because all parallel terminal operations ignore order
B. Optional.of(2) because findFirst respects encounter order
C. Optional.empty() because findFirst cannot operate in parallel
D. Optional.of(8) because a middle partition is processed first

48 Which expression defines a reduction that is valid for both sequential and parallel execution?

Defining reduction Hard
A. numbers.reduce(0, (a, b) -> a - b)
B. numbers.reduce(1, Integer::sum)
C. numbers.reduce(0, Integer::sum)
D. numbers.reduce(new ArrayList<>(), (a, b) -> { a.add(b); return a; })

49 What value is returned by the following parallel reduction?

List<String> words = List.of("a", "bb", "ccc", "dddd");

int total = words.parallelStream().reduce(0, (n, s) -> n + s.length(), Integer::sum);

Calculating a value using reduce Hard
A. 4
B. 0
C. 10
D. 24

50 In this parallel collection, what is the purpose of the third argument?

words.parallelStream().collect(HashMap::new, (m, w) -> m.merge(w, 1, Integer::sum), (left, right) -> right.forEach((k, v) -> left.merge(k, v, Integer::sum)));

Describing the process for decomposing and then merging work Hard
A. It sorts each partial map before the terminal result is returned
B. It merges partial frequency maps produced by separate parallel tasks
C. It supplies an empty frequency map to every stream element
D. It transforms each input word before the word enters a partial map

51 Some Employee objects have a null department. Which pipeline extracts the names of existing departments without throwing NullPointerException?

Extracting data from an object using map Hard
A. employees.stream().map(Employee::department).map(Department::name).filter(Objects::nonNull).toList()
B. employees.stream().filter(Objects::nonNull).map(Employee::department).map(Department::name).toList()
C. employees.stream().filter(e -> e.department().name() != null).map(Employee::department).toList()
D. employees.stream().map(Employee::department).filter(Objects::nonNull).map(Department::name).toList()

52 How should sorted(), limit(5), and collect(...) be classified in a stream pipeline?

Describing the types of stream operations Hard
A. sorted() is short-circuiting intermediate, limit(5) is stateful terminal, and collect(...) is stateless
B. sorted() is stateful terminal, limit(5) is stateless intermediate, and collect(...) is terminal
C. sorted() is stateful intermediate, limit(5) is short-circuiting stateful intermediate, and collect(...) is terminal
D. sorted() is stateless intermediate, limit(5) is short-circuiting terminal, and collect(...) is intermediate

53 Suppose loadDefault() increments a counter and returns "guest". What happens in Optional.of("admin").orElse(loadDefault())?

Describing the Optional class Hard
A. loadDefault() executes, but "admin" is returned
B. loadDefault() does not execute, and "admin" is returned
C. loadDefault() does not execute, and "guest" is returned
D. loadDefault() executes, and "guest" is returned

54 What are the counter values immediately before and after findFirst()?

AtomicInteger tested = new AtomicInteger();

IntStream stream = IntStream.range(1, 10).filter(n -> { tested.incrementAndGet(); return n % 3 == 0; });

int before = tested.get();

int value = stream.findFirst().orElse(-1);

int after = tested.get();

Describing lazy processing Hard
A. before is 9 and after is 9
B. before is 3 and after is 3
C. before is 0 and after is 3
D. before is 0 and after is 9

55 Consider this comparator:

Comparator.comparing(Person::lastName, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(Person::id).reversed()

What does the final reversed() do?

Sorting a stream Hard
A. It reverses encounter order without changing either key comparison
B. It reverses only the last-name comparison while preserving nulls last
C. It reverses the complete comparator, including null placement and both sort keys
D. It reverses only the id comparison while preserving ascending last names

56 What happens when this pipeline executes?

Map<Integer, String> m = Stream.of("aa", "ab").collect(Collectors.toMap(String::length, Function.identity()));

Saving results to a collection using the collect method Hard
A. It stores "ab" because toMap keeps the last duplicate value
B. It creates one key associated with a list containing both strings
C. It stores "aa" because toMap keeps the first duplicate value
D. It throws IllegalStateException because both strings produce the same key

57 All input words have length at most 3. How do these collectors differ?

partitioningBy(w -> w.length() > 3)

groupingBy(w -> w.length() > 3)

Grouping and partitioning data using the Collectors class Hard
A. Both collectors include true with a null value rather than an empty list
B. groupingBy includes both Boolean keys, while partitioningBy may omit true
C. partitioningBy includes both Boolean keys, while groupingBy may omit true
D. Both collectors omit true because no input satisfies the predicate

58 A class overloads submit(Runnable task) and <T> submit(Callable<T> task). Assume service.run() returns a String. What happens with submit(() -> service.run())?

Program to implement Lambda operations Hard
A. The Runnable overload is selected because the body is a method invocation
B. The overload is selected at runtime from the value returned by service.run()
C. Compilation fails because the expression lambda is compatible with both overloads
D. The Callable<String> overload is selected because the expression returns a value

59 What is the behavior of Stream.generate(() -> 1).distinct().limit(2).count()?

Chaining multiple methods together Hard
A. It returns 2 because limit counts source elements before applying distinct
B. It returns 1 because distinct removes every duplicate before limit executes
C. It does not terminate because the stream can never produce a second distinct value
D. It throws IllegalStateException because distinct cannot process infinite streams

60 Why is this mutable parallel reduction incorrect?

values.parallelStream().reduce(new ArrayList<Integer>(), (list, x) -> { list.add(x); return list; }, (a, b) -> { a.addAll(b); return a; });

Describing the process for decomposing and then merging work Hard
A. The identity must already contain one representative stream element
B. The same mutable identity can be shared and modified by multiple parallel tasks
C. The accumulator cannot return the same list instance that it receives
D. The combiner must create an immutable list before adding partial results