Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

I want to have a reversed list view on a list (in a similar way than List#sublist provides a sublist view on a list). Is there some function which provides this functionality?

I don't want to make any sort of copy of the list nor modify the list.

It would be enough if I could get at least a reverse iterator on a list in this case though.

Also, I know how to implement this myself. I'm just asking if Java already provides something like this.

Demo implementation:

static <T> Iterable<T> iterableReverseList(final List<T> l) {

    return new Iterable<T>() {

        public Iterator<T> iterator() {

            return new Iterator<T>() {

                ListIterator<T> listIter = l.listIterator(l.size());                    

                public boolean hasNext() { return listIter.hasPrevious(); }

                public T next() { return listIter.previous(); }

                public void remove() { listIter.remove(); }                 

            };

        }

    };

}

I just have found out that some List implementations have descendingIterator() which is what I need. Though there is no general such implementation for List. Which is kind of strange because the implementation I have seen in LinkedList is general enough to work with any List.

1 Answer

0 votes
by (46k points)

Guava presents this: Lists.reverse(List)

List<String> letters = ImmutableList.of("a", "b", "c");

List<String> reverseView = Lists.reverse(letters); 

System.out.println(reverseView); // [c, b, a]

Unlike Collections.reverse, this is a view... it doesn't modify the ordering of elements in the initial list. Additionally, with an original list that is modifiable, modifications to both the original list and the view are shown in the other.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Aug 6, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...