DaveAKing / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Add `only()` and `onlyMatch(Predicate<? super E> predicate)` to `FluentIterable`. #1544

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
There are `Itera*s.getOnlyElement(*)`, but no equivalent methods on the fluent 
wrapper.

I'd like to see both `only()` to retrieve the single element in the wrapped 
iterable, and `onlyMatch(Predicate)` to retrieve the single element in the 
wrapped iterable that matches the predicate.

`only()` should return `Optional`, just like `first()` and `last()` do.

I'm not sure on the return type of `onlyMatch(Predicate)`, though: Both 
`Optional` (like `firstMatch(Predicate)`) and throwing exceptions (like 
`Iterables.getOnlyElement(Iterable)`) have their use cases. The latter provides 
some kind of built-in constraint enforcing, but I wouldn't sacrifice the first 
for it; maybe two, cleverly-named methods are doable.

Original issue reported on code.google.com by j...@nwsnet.de on 25 Sep 2013 at 4:23

GoogleCodeExporter commented 9 years ago
fluentIterable.onlyMatch(predicate) would be equivalent to 
fluentIterable.filter(predicate).only(), wouldn't it?

Original comment by SeanPFl...@googlemail.com on 25 Sep 2013 at 4:25

GoogleCodeExporter commented 9 years ago
Indeed, given that it should return `Optional` instead of throwing exceptions.

Then again, I'm not sure if `matchOnly` would allow the implementation to take 
a shortcut in order to exit early (in the case of multiple matching elements) 
after the predicate returned true twice.

Original comment by j...@nwsnet.de on 25 Sep 2013 at 7:25

GoogleCodeExporter commented 9 years ago
filter(predicate) is lazy, so filter(predicate).only() would get that same 
"shortcut" for free anyway.

Original comment by lowas...@google.com on 25 Sep 2013 at 7:28

GoogleCodeExporter commented 9 years ago

Original comment by kak@google.com on 25 Sep 2013 at 7:30

GoogleCodeExporter commented 9 years ago

Original comment by lowas...@google.com on 25 Sep 2013 at 7:46

GoogleCodeExporter commented 9 years ago
Ah, wasn't completely sure about the laziness.

Original comment by j...@nwsnet.de on 25 Sep 2013 at 9:51

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<issue id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:12

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:08