Nicolai Parlog @nipafx.dev · Apr 1

Java stream's terminal operations `findFirst` and `findAny` are neat but one use cases isn't covered: "find the only one" - a terminal operation you'd use after a filter that's supposed to let exaxctly one element pass through. There's now a JDK preview with that operation, named `highlander`. ⚔️

36 likes 4 replies

?

Replies

Rune Flobakk · Apr 1

Jokes aside, I actually made a similar collector 😜, designed to intentionally fail in the event of the set up pipeline resulting in more than one element: javadoc.io/static/no.di... Better to fail early than risk serving wrong data using findFirst/Any, if filtering is not specific enough.

Draken · Apr 1

May we use a Lambert function as parameter?

GreenEyed · Apr 1

Is it really that different from findFirst().orElseThrow() ? To make it really something, I'd include the filter in the "highlander" and reduce 3 to 1. Else I don't see much gain 🤷🏻‍♂️

Lukas Eder · Apr 1

It's a bit confusing. It could also mean skip(1) as that is what competing highlanders do with each other.