This works as long as the iterator implements reverse. There was recently a discussion here about the difficulties of adding a generic last method: Getting the last element of an iterator. I planned to submit a PR but as explained in that thread I couldn’t find an implementation that was performant and backward-compatible.
As a workaround @mschauer suggested foldl((_, y) -> y, itr), which also works fine here:
I realize that a general O(1)last method is not possible in most cases, and the foldl equivalents would be O(n) if I understand correctly. In this specific case of a ProductIterator, it feels like it should support fetching the last element in O(1) time, unless there are some corner cases that I am missing out on?
The method last(it, 1) seems to rely on actually collecting the elements of the iterator, which may be avoided in many cases?