1Z0-819 Core APIs & Data Manipulation 5 — Questions and Answers
Question 1: Which method on `Optional<T>` executes an action if a value is present and does nothing otherwise?
- ifPresent() (Correct answer)
- orElse()
- filter()
- map()
Correct answer: ifPresent()
`ifPresent(Consumer)` calls the consumer with the value when present and is a no-op when the Optional is empty.
Question 2: What does `TreeSet` use to order its elements by default?
- Natural ordering via Comparable (Correct answer)
- Insertion order
- Hash code order
- Random order
Correct answer: Natural ordering via Comparable
`TreeSet` relies on the elements' natural ordering (their `Comparable` implementation) unless a custom `Comparator` is provided at construction.
Question 3: Which statement about `StringJoiner` is true?
- It can be constructed with a delimiter, optional prefix, and optional suffix (Correct answer)
- It is a subclass of StringBuilder
- It only accepts numeric values
- It throws an exception when empty
Correct answer: It can be constructed with a delimiter, optional prefix, and optional suffix
`StringJoiner(delimiter, prefix, suffix)` builds a joined string with optional surrounding tokens, and returns the empty-value string (not an exception) when no elements are added.
Question 4: What is the output of: `List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.remove(1);` — what remains?
- [1] (Correct answer)
- [2]
- [1, 2]
- Throws IndexOutOfBoundsException
Correct answer: [1]
`list.remove(1)` uses the index overload (not the object overload) because the argument is an `int`, removing the element at index 1 (value 2), leaving [1].
Question 5: Which `Stream` collector groups elements into a `Map<Boolean, List<T>>` based on a predicate?
- Collectors.partitioningBy() (Correct answer)
- Collectors.groupingBy()
- Collectors.mapping()
- Collectors.toMap()
Correct answer: Collectors.partitioningBy()
`Collectors.partitioningBy(Predicate)` always produces a two-partition map with `true` and `false` keys.
Question 6: What is the result of `Duration.between(LocalTime.of(10,0), LocalTime.of(9,0)).toHours()`?
- -1 (Correct answer)
- 1
- 23
- Throws DateTimeException
Correct answer: -1
`Duration.between` subtracts the start from the end; since end (9:00) is before start (10:00), the result is a negative duration of -1 hour.
Question 7: Which method converts an `IntStream` to a `Stream<Integer>` (boxed)?
- boxed() (Correct answer)
- mapToObj(Integer::valueOf)
- toStream()
- asStream()
Correct answer: boxed()
`IntStream.boxed()` is the idiomatic way to convert a primitive `IntStream` to a `Stream<Integer>`.
Which method on `Optional` executes an action if a value is present and does nothing otherwise?