up vote10down votefavorite |
I am trying to use Java 8 Take this code:
This code finds a Changing the filter line to:
Will throw a I would like it to throw an error if there are multiple matches, though. Is there a way to do this?
|
||||||||||||||||
|
6 Answers
up vote13down voteaccepted |
Technically there‘s an ugly ‘workaround‘ that involves What I do in these cases is just collecting it in a list, like this:
I am not aware of a way to do this in the API, meanwhile I will work on another example involving a custom element. Update, You should create your own
What it does is:
Used as:
You can then customize this New update, I revised my old answer once more for
|
||||||||||||||||
|
up vote9down vote |
Wow, such complexity! :-) The other answers that involve writing a custom Collector are probably more efficient (such as Louis Wasserman‘s, +1), but if you want brevity, I‘d suggest the following:
Then verify the size of the result list.
|
||||||||
|
up vote6down vote |
You could roll your own Collector for this:
...or using your own
|
||||||||||||||||||||
|
up vote5down vote |
The "escape hatch" operation that lets you do weird things that are not otherwise supported by streams is to ask for an
Guava has a convenience method to take an
|
|||
add a comment |
up vote3down vote |
The exception is thrown by
which throws a Or you could use a reduction combined with an optional:
The reduction essentially returns:
The result is then wrapped in an optional. But the simplest solution would probably be to just collect to a collection, check that its size is 1 and get the only element.
|
||||||||
|
up vote0down vote |
Have you tried this
|
||||
|