The decision
A shipping form may preselect a route only when exactly one quote qualifies for the budget. If two quotes qualify, leave the choice to the customer, even if both have the same route code.
Read the Kotlin
Count qualifying quotes before reading the route
The braces after singleOrNull test one quote at a time. Count matches, including repeated records for the same route. With exactly one match, Kotlin returns that Quote and ?.route reads its name. With either zero or two matches the result is null. Equal route names never merge the quotes.
listOf(5, 9, 5).singleOrNull { it <= 5 } // null
listOf(6, 9, 5).singleOrNull { it <= 5 } // 5Separate existence from uniqueness
A button that lights up when any option is affordable should stay lit when a second option arrives. any { ... } returns a Boolean and can stop on its first match. Testing whether singleOrNull returned a value would turn the button off again on the second match. Two qualifying rows make an effective review case.
Choose how selection failure reaches callers
Use single when exactly one match is an invariant and a broken invariant should throw. No matching element raises NoSuchElementException, and a second raises IllegalArgumentException. Use singleOrNull when callers handle both outcomes as absence. A caller that must distinguish “sold out” from “several choices” needs a richer result.
The full example
import java.util.List;
class Lesson {
record Quote(String route, int cents) {}
static String onlyRoute(List<Quote> quotes, int budget) {
var hits = quotes.stream().filter(q -> q.cents() <= budget)
.limit(2).toList();
return hits.size() == 1 ? hits.getFirst().route() : null;
}
}data class Quote(val route: String, val cents: Int)
fun onlyRoute(quotes: List<Quote>, budget: Int): String? =
quotes.singleOrNull { it.cents <= budget }?.routeInputs and outcomes
| Input | Outcome | Why it matters |
|---|---|---|
Bike 300, Van 500 · budget 300 | Bike | The inclusive limit admits Bike. |
Bike 300, Van 500 · budget 700 | null | Two affordable quotes make the choice ambiguous. |
No quotes | null | A route cannot be preselected. |
Walk through the code
- The Java stream collects at most two hits. One hit identifies a route; the second already proves ambiguity.
- singleOrNull with a predicate asks that same cardinality question directly. The safe call selects route only if the operation found exactly one qualifying Quote.
The Java habit
firstOrNull accepts the first affordable quote even if a second affordable quote follows it. That port turns a user decision into an automatic selection.
When to choose differently
If the screen must distinguish 'no service' from 'choose a route', null merges two different outcomes. Model absence and ambiguity separately.