Skip to content

Core: Use toOptional and onlyElement methods in MoreCollectors#16254

Open
ebyhr wants to merge 1 commit into
apache:mainfrom
ebyhr:ebi/guava-more-collectors
Open

Core: Use toOptional and onlyElement methods in MoreCollectors#16254
ebyhr wants to merge 1 commit into
apache:mainfrom
ebyhr:ebi/guava-more-collectors

Conversation

@ebyhr
Copy link
Copy Markdown
Member

@ebyhr ebyhr commented May 8, 2026

The existing findFirst silently hides multiple matching elements.

This PR replaces it with Guava MoreCollectors:

onlyElement method:

A collector that takes a stream containing exactly one element and returns that element. The returned collector throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.

toOptional method:

A collector that converts a stream of zero or one elements to an Optional.
Throws: IllegalArgumentException - if the stream consists of two or more elements.
Throws: NullPointerException - if any element in the stream is null.

I only updated a few places to demonstrate how to use them.

@github-actions github-actions Bot added the core label May 8, 2026
Copy link
Copy Markdown
Contributor

@singhpk234 singhpk234 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there use case for this for non test scenarios ?
On an orthogonal note it seems like the tests are just fine without this

@ebyhr ebyhr force-pushed the ebi/guava-more-collectors branch from cf44360 to 3c8d443 Compare May 8, 2026 19:19
@ebyhr
Copy link
Copy Markdown
Member Author

ebyhr commented May 8, 2026

@singhpk234 Yes, the same pattern persists even in non-test code. I've made additional modifications, and there are actually more places where this pattern occurs.

@ebyhr ebyhr force-pushed the ebi/guava-more-collectors branch from 3c8d443 to 91ae9b1 Compare May 8, 2026 23:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants