maidh91 / guava-libraries

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

Iterators.last method #481

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
It would be nice to have a last() method for the Iterators class with the same 
declaration as find() has:

Iterators.last(Iterator<T> iterator, Predicate<? super T> predicate)
and

Iterators.last(Iterator<T> iterator, Predicate<? super T> predicate, T 
defaultValue) 

and of course the find() could be first() instead of find, but this isn't the 
issue why I'm writing.

This method would return the last element from the Iterator on which the 
Predicate method returned true (satisfied the predicate).

With this method it would be easy to write a min and max functions with the 
following code:

T minValue = Iterators.last(items.iterator(), Predicates.min());

and

T  maxValue = Iterators.last(items.iterator(), Predicates.max());

the Predicates.min() would return true if the next element from the iterator is 
smaller then the previous, and the Predicates.max() would do the opposite.

Original issue reported on code.google.com by ikara...@gmail.com on 19 Nov 2010 at 12:21

GoogleCodeExporter commented 9 years ago
[deleted comment]
GoogleCodeExporter commented 9 years ago
of course it could be used for anything which needs the last item from the 
elements.

Original comment by ikara...@gmail.com on 19 Nov 2010 at 1:20

GoogleCodeExporter commented 9 years ago
Why not use Iterators.filter(Iterator, Predicate) or Ordering.min/max(Iterable) 
?

Original comment by amer...@gmail.com on 19 Nov 2010 at 1:51

GoogleCodeExporter commented 9 years ago
[deleted comment]
GoogleCodeExporter commented 9 years ago
ohh, I see. thanks :)

Original comment by ikara...@gmail.com on 19 Nov 2010 at 2:04

GoogleCodeExporter commented 9 years ago
It looks like @amertum solved the issue that generated this report.

Just one thing I thought I'd point out from the original report as a caution... 
 In the sample code, Predicates.min() and Predicates.max() would have to be 
stateful, which is strongly discouraged by the contract of Predicate.apply():

"This method is generally expected, but not absolutely required, to have the 
following properties:
 - Its execution does not cause any observable side effects.
 - The computation is consistent with equals; that is, Objects.equal(a, b) implies that predicate.apply(a) == predicate.apply(b))."

Original comment by boppenh...@google.com on 20 Nov 2010 at 5:31

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

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

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

GoogleCodeExporter commented 9 years ago

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