Improved means for reverse-iterating a list.

Description

Provide a simplified means for iterating a list in reverse order, in particular supporting enhanced for loops.

We already have com.globalmentor.collections.iterators.ReverseIterator, which should be made package-private. Add the following convenience methods:

  • ListIterator<E> Iterators.reverse(ListIterator<E>)

  • Iterable<E> Iterables.backwards(Supplier<? extends ListIterator<E>>)

  • Iterable<E> Lists.backwards(List<E>) (which might delegate to the Iterables version)

Compare to Guava Lists.reverse(), although this solution will be more lightweight.

See also Iterating through a list in reverse order in java (Stack Overflow) and Iterating Backward Through a List (Baeldung).

Refer to this note on naming from the OED. Probably “reversing” would be a better name that “backwards”.

Environment

None

Activity

Garret Wilson 
September 27, 2022 at 9:48 PM

The value of Iterable<E> Iterables.backwards(Supplier<? extends ListIterator<E>>) is questionable. It would look something like this (and “reversing” would probably be a better name):

This seems almost a little too roundabout. Mostly users will just want to reverse a list—that’s about the only source of a list iterator anyway. The only utility here is that the lambda automatically advances the list iterator to its end before creating the reversed version. But coming from a list we would use list.listIterator(list.size()) anyway. So perhaps just a end(Iterator<>) method might be useful to move it to its end, but it’s not clear who would want to use that if we can create a list iterator at the end to begin with. So let’s just leave out this generalized Iterable<> version altogether for the meantime.

Fixed

Details

Assignee

Reporter

Components

Priority

Created September 27, 2022 at 4:28 PM
Updated September 27, 2022 at 11:45 PM
Resolved September 27, 2022 at 11:45 PM