Unit 1: Collections, Streams, Filters, and Lambdas - Practice Quiz
1 What is the main purpose of the Builder pattern in Java?
2
Which statement prints every element of a list named names using lambda syntax?
names.collect(name -> System.out.println(name));
names.filter(name -> System.out.println(name));
names.map(name -> System.out.println(name));
names.forEach(name -> System.out.println(name));
3 What does a Java stream primarily represent?
4 Which stream operation selects only the elements that satisfy a lambda condition?
reduce
filter
sorted
map
5
What does numbers.stream().filter(n -> n > 10) produce?
6 What does method chaining mean in a Java stream pipeline?
7 Which sequence correctly describes a basic stream pipeline?
8 Which collection method directly creates a parallel stream?
parallelize()
parallelStream()
parallel()
streamParallel()
9 What is reduction in the Java Stream API?
10
What is the result of Stream.of(1, 2, 3).reduce(0, (a, b) -> a + b)?
5
3
0
6
11 In parallel stream processing, what happens after work is divided into smaller tasks?
12
Given a stream of Person objects, which operation extracts each person's name?
.filter(person -> person.getName())
.reduce(person -> person.getName())
.map(person -> person.getName())
.sorted(person -> person.getName())
13 Which of the following is an intermediate stream operation?
map
count
collect
forEach
14 Which of the following is a terminal stream operation?
distinct
sorted
collect
filter
15
Why is the Optional class commonly used?
16 When are intermediate stream operations normally executed?
17 Which operation sorts stream elements according to their natural order?
ordered()
arranged()
sorted()
compared()
18
Which expression saves stream elements into a List?
.map(Collectors.toList())
.collect(Collectors.toSet())
.reduce(Collectors.toList())
.collect(Collectors.toList())
19 Which collector divides elements into two groups based on a predicate?
Collectors.partitioningBy(...)
Collectors.mapping(...)
Collectors.joining(...)
Collectors.groupingBy(...)
20
Which lambda expression correctly represents an operation that multiplies an integer x by 2?
x <- x * 2
x => x * 2
x -> x * 2
x :: x * 2
21 Which situation most strongly justifies using the Builder pattern in Java?
22
What is printed by the following code?
List<String> names = Arrays.asList("Ana", "Bob", "Cara");
names.forEach(name -> System.out.print(name + " "));
23
Which statement correctly describes a Java Stream?
24
Which expression creates a stream containing only positive integers from numbers?
25
What is the result of this pipeline?
List<String> result = words.stream()
.filter(w -> w.length() > 3)
.map(String::toUpperCase)
.sorted()
.toList();
26 In a stream pipeline, which operation normally represents the terminal operation?
27 Which code converts a collection into a parallel stream pipeline?
28 What is the purpose of a reduction operation on a stream?
29
What value is assigned to total?
int total = Stream.of(2, 4, 6)
.reduce(1, (a, b) -> a + b);
30 Which description best matches fork/join processing used by parallel streams?
31
Which expression produces a stream of email addresses from a stream of Customer objects?
32
Which classification is correct for filter, map, and count?
33
Why might a method return Optional<String> instead of returning String directly?
34
When are intermediate stream operations such as filter and map generally executed?
35 Which pipeline sorts integers in descending order and collects them into a list?
36
Which statement collects the names with length at least five into a mutable ArrayList?
37
What does the following collector produce?
Map<Boolean, List<Integer>> groups = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
38 Which collector groups employees by their department name?
39
Which lambda correctly represents a Predicate<Integer> that accepts even numbers?
40 Which pipeline calculates the average length of non-blank strings while avoiding an exception when no strings match?
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?
builder.items directly and return it through an unmodifiable view
Report constructor using List.copyOf(builder.items)
builder.items directly and return a new list from the getter
42
Assume result is a thread-safe list. What is guaranteed after executing List.of(1, 2, 3, 4).parallelStream().forEach(result::add)?
result must contain the values in reverse encounter order
result contains all four values exactly once, but their order is unspecified
result contains all four values exactly once in encounter order
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();
findFirst() returns Optional.of(1) because streams can execute repeatedly
findFirst() throws IllegalStateException because the stream was already consumed
findFirst() returns Optional.empty() because count() exhausted the elements
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?
r always contains [2, 4, 6, 8] because increments occur before testing
r always contains [1, 3, 5, 7] because the source is ordered
r has four elements, but which values pass may vary between executions
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()
[1]
[3, 5]
[5]
[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();
sum is 56 and mapped.get() is 3
sum is 20 and mapped.get() is 6
sum is 56 and mapped.get() is 6
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()?
Optional.of(2) because findFirst respects encounter order
Optional.of(8) because a middle partition is processed first
Optional.empty() because findFirst cannot operate in parallel
48 Which expression defines a reduction that is valid for both sequential and parallel execution?
numbers.reduce(new ArrayList<>(), (a, b) -> { a.add(b); return a; })
numbers.reduce(1, Integer::sum)
numbers.reduce(0, (a, b) -> a - b)
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);
10
0
24
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)));
51
Some Employee objects have a null department. Which pipeline extracts the names of existing departments without throwing NullPointerException?
employees.stream().map(Employee::department).filter(Objects::nonNull).map(Department::name).toList()
employees.stream().filter(e -> e.department().name() != null).map(Employee::department).toList()
employees.stream().filter(Objects::nonNull).map(Employee::department).map(Department::name).toList()
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?
sorted() is stateful intermediate, limit(5) is short-circuiting stateful intermediate, and collect(...) is terminal
sorted() is short-circuiting intermediate, limit(5) is stateful terminal, and collect(...) is stateless
sorted() is stateless intermediate, limit(5) is short-circuiting terminal, and collect(...) is intermediate
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())?
loadDefault() executes, and "guest" is returned
loadDefault() does not execute, and "admin" is returned
loadDefault() does not execute, and "guest" is returned
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();
before is 9 and after is 9
before is 0 and after is 3
before is 3 and after is 3
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?
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()));
IllegalStateException because both strings produce the same key
"ab" because toMap keeps the last duplicate value
"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)
groupingBy includes both Boolean keys, while partitioningBy may omit true
true with a null value rather than an empty list
partitioningBy includes both Boolean keys, while groupingBy may omit true
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())?
Callable<String> overload is selected because the expression returns a value
service.run()
Runnable overload is selected because the body is a method invocation
59
What is the behavior of Stream.generate(() -> 1).distinct().limit(2).count()?
1 because distinct removes every duplicate before limit executes
IllegalStateException because distinct cannot process infinite streams
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; });
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →