Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iterables.getFirst(Iterable) (with no default value) #921

Closed
gissuebot opened this issue Oct 31, 2014 · 7 comments
Closed

Iterables.getFirst(Iterable) (with no default value) #921

gissuebot opened this issue Oct 31, 2014 · 7 comments

Comments

@gissuebot
Copy link

Original issue created by olivier.miel on 2012-03-02 at 02:04 PM


It would be sweet to have a Iterables#getFirst method which does not require a default value but instead throws a NoSuchElementException if used on an empty collection ; there is such a #getLast method after all.

@gissuebot
Copy link
Author

Original comment posted by stephan202 on 2012-03-02 at 02:46 PM


Wouldn't that be equivalent to calling #iterator().next()? The latter is very idiomatic, so I'm not sure there's any benefit in adding such a method.

@gissuebot
Copy link
Author

Original comment posted by stephan202 on 2012-03-02 at 02:49 PM


See also comments 18 and 20 of Issue 217.

@gissuebot
Copy link
Author

Original comment posted by kevinb@google.com on 2012-03-02 at 02:49 PM


stephan has it.


Status: WorkingAsIntended

@gissuebot
Copy link
Author

Original comment posted by PhotoSlanec on 2013-01-10 at 01:36 AM


I think the defending point of view here is that while #iterator().next() is fairly common and the usage is simple, it doesn't express the intent so well.
We don't want to iterate over the Collection, we want to get the first item and the Iterables#getFirst() method would express this in a much clearer way.
Also, it's just inconsistent to use Iterables#getLast() and sometimes Iterables#get(), but to have to use #iterator().next() while the Iterables version would be in place.

@gissuebot
Copy link
Author

Original comment posted by wasserman.louis on 2014-02-23 at 12:43 AM


Issue #1679 has been merged into this issue.

@gissuebot
Copy link
Author

Original comment posted by android.money on 2014-02-23 at 12:50 AM


I agree with #4. By that measure, why is there a getOnlyElement()? iterable().next() would also return that.

@gissuebot
Copy link
Author

Original comment posted by stephan202 on 2014-02-23 at 10:27 AM


why is there a getOnlyElement()?

That method does more than iterable().next(), because it throws an IllegalArgumentException if the iterable contains multiple elements. One should use it primarily in situations where having more than one element constitutes a programming error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant