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 construct complex objects step by step
B. To convert objects into streams
C. To sort objects automatically
D. To execute methods in parallel

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

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

3 What does a Java stream primarily represent?

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

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

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

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 stream containing numbers greater than 10
C. A sum of numbers greater than 10
D. A count of numbers greater than 10

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

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

7 Which sequence correctly describes a basic stream pipeline?

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

8 Which collection method directly creates a parallel stream?

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

9 What is reduction in the Java Stream API?

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

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

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

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 tasks become sequential streams
B. The partial results are combined
C. The original collection is deleted
D. The intermediate results are ignored

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

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

13 Which of the following is an intermediate stream operation?

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

14 Which of the following is a terminal stream operation?

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

15 Why is the Optional class commonly used?

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

16 When are intermediate stream operations normally executed?

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

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

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

18 Which expression saves stream elements into a List?

Saving results to a collection using the collect method Easy
A. .map(Collectors.toList())
B. .collect(Collectors.toSet())
C. .reduce(Collectors.toList())
D. .collect(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.partitioningBy(...)
B. Collectors.mapping(...)
C. Collectors.joining(...)
D. Collectors.groupingBy(...)

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 is created exclusively through inheritance
B. An object has many optional configuration fields
C. An object must contain only static methods
D. An object requires one fixed constructor argument

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. The list object reference
B. Ana, Bob, Cara
C. Ana Bob Cara
D. name name name

23 Which statement correctly describes a Java Stream?

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

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

Filtering a collection using lambda expressions Medium
A. numbers.stream().map(n -> n > 0)
B. numbers.stream().collect(n -> n > 0)
C. numbers.stream().filter(n -> n > 0)
D. numbers.stream().reduce(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. Uppercase words longer than three characters, sorted
B. Words shorter than three characters, sorted
C. All words converted to uppercase, in original order
D. Only the first matching word, converted to uppercase

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 produces a final result
B. The operation that declares the collection type
C. The operation that creates the source stream
D. The operation that selects a lambda parameter

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

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

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

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

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. 7
B. 12
C. 13
D. 11

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. Split work into subtasks, then combine their results
C. Run one task repeatedly until the source is empty
D. Execute only the first subtask and discard the rest

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.reduce(Customer::getEmail)
B. customers.filter(Customer::getEmail)
C. customers.sorted(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. Filter and count are intermediate; map is terminal
B. Map and count are intermediate; filter is terminal
C. All three operations are 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 represent a value that may be absent
B. To convert the string into a parallel stream
C. To guarantee that the string is never empty
D. To make all string operations immutable

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

Describing lazy processing Medium
A. Before the stream source is created
B. Only after the stream variable is discarded
C. When a terminal operation consumes the stream
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().reverse(Comparator.reverseOrder()).toList()
B. values.stream().ordered(Comparator.reverseOrder()).toList()
C. values.stream().sort(Comparator.reverseOrder()).toList()
D. values.stream().sorted(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).collect(Collectors.toList())
C. names.stream().filter(n -> n.length() >= 5).collect(Collectors.toCollection(ArrayList::new))
D. names.stream().filter(n -> n.length() >= 5).reduce(new ArrayList<>(), ArrayList::add)

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. Two lists keyed by whether numbers are even
B. Lists grouped by each distinct numeric value
C. A map containing only the even numbers
D. A single list sorted by the parity of numbers

38 Which collector groups employees by their department name?

Grouping and partitioning data using the Collectors class Medium
A. Collectors.groupingBy(Employee::getDepartment)
B. Collectors.partitioningBy(Employee::getDepartment)
C. Collectors.joining(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 == 0
B. n -> System.out.println(n)
C. n -> Integer.valueOf(n)
D. n -> n + 2

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().reduce(0, (a, s) -> a + s.length()).average()
B. words.stream().filter(s -> !s.isBlank()).mapToInt(String::length).average()
C. words.stream().mapToInt(String::length).filter(s -> !s.isBlank()).average()
D. words.stream().filter(s -> !s.isBlank()).map(String::length).sum()

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. Store builder.items directly and return it through an unmodifiable view
B. Copy the list in the Report constructor using List.copyOf(builder.items)
C. Store builder.items directly and return a new list from the getter
D. Copy the list in the builder setter but store the builder's copy directly

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 must contain the values in reverse encounter order
B. result contains all four values exactly once, but their order is unspecified
C. result contains all four values exactly once in encounter order
D. result may omit values because forEach is non-deterministic

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() returns Optional.of(1) because streams can execute repeatedly
B. findFirst() throws IllegalStateException because the stream was already consumed
C. findFirst() returns Optional.empty() because count() exhausted the elements
D. findFirst() throws NoSuchElementException because no elements remain

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 always contains [1, 3, 5, 7] because the source is ordered
C. r has four elements, but which values pass may vary between executions
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. [1]
B. [3, 5]
C. [5]
D. [3]

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 3
B. sum is 20 and mapped.get() is 6
C. sum is 56 and mapped.get() is 6
D. sum is 20 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. Optional.of(2) because findFirst respects encounter order
B. Optional.of(8) because a middle partition is processed first
C. Optional.empty() because findFirst cannot operate in parallel
D. Any even value because all parallel terminal operations ignore order

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

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

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. 10
B. 0
C. 24
D. 4

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 transforms each input word before the word enters a partial map
D. It supplies an empty frequency map to every stream element

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).filter(Objects::nonNull).map(Department::name).toList()
B. employees.stream().filter(e -> e.department().name() != null).map(Employee::department).toList()
C. employees.stream().filter(Objects::nonNull).map(Employee::department).map(Department::name).toList()
D. employees.stream().map(Employee::department).map(Department::name).filter(Objects::nonNull).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 stateful intermediate, limit(5) is short-circuiting stateful intermediate, and collect(...) is terminal
B. sorted() is short-circuiting intermediate, limit(5) is stateful terminal, and collect(...) is stateless
C. sorted() is stateless intermediate, limit(5) is short-circuiting terminal, and collect(...) is intermediate
D. sorted() is stateful terminal, limit(5) is stateless intermediate, and collect(...) is terminal

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, and "guest" is returned
B. loadDefault() does not execute, and "admin" is returned
C. loadDefault() does not execute, and "guest" is returned
D. loadDefault() executes, but "admin" 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 0 and after is 3
C. before is 3 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 the complete comparator, including null placement and both sort keys
B. It reverses only the last-name comparison while preserving nulls last
C. It reverses only the id comparison while preserving ascending last names
D. It reverses encounter order without changing either key comparison

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 throws IllegalStateException because both strings produce the same key
B. It stores "ab" because toMap keeps the last duplicate value
C. It creates one key associated with a list containing both strings
D. It stores "aa" because toMap keeps the first duplicate value

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. groupingBy includes both Boolean keys, while partitioningBy may omit true
B. Both collectors include true with a null value rather than an empty list
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 Callable<String> overload is selected because the expression returns a value
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 Runnable overload is selected because the body is a method invocation

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

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

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 accumulator cannot return the same list instance that it receives
C. The same mutable identity can be shared and modified by multiple parallel tasks
D. The combiner must create an immutable list before adding partial results