How to get a reversed list view on a list in Java?

JavaListCollectionsIteratorReverse

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Use the .clone() method on your List. It will return a shallow copy, meaning that it will contain pointers to the same objects, so you won't have to copy the list. Then just use Collections.

Ergo,

Collections.reverse(list.clone());

If you are using a List and don't have access to clone() you can use subList():

List<?> shallowCopy = list.subList(0, list.size());
Collections.reverse(shallowCopy);

Solution 2 - Java

Guava provides 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 purely a view... it doesn't alter the ordering of elements in the original list. Additionally, with an original list that is modifiable, changes to both the original list and the view are reflected in the other.

Solution 3 - Java

If i have understood correct then it is one line of code .It worked for me .

 Collections.reverse(yourList);

Solution 4 - Java

Its not exactly elegant, but if you use List.listIterator(int index) you can get a bi-directional ListIterator to the end of the list:

//Assume List<String> foo;
ListIterator li = foo.listIterator(foo.size());

while (li.hasPrevious()) {
   String curr = li.previous();
}

Solution 5 - Java

I use this:

public class ReversedView<E> extends AbstractList<E>{

    public static <E> List<E> of(List<E> list) {
        return new ReversedView<>(list);
    }

    private final List<E> backingList;

    private ReversedView(List<E> backingList){
        this.backingList = backingList;
    }

    @Override
    public E get(int i) {
        return backingList.get(backingList.size()-i-1);
    }

    @Override
    public int size() {
        return backingList.size();
    }

}

like this:

ReversedView.of(backingList) // is a fully-fledged generic (but read-only) list

Solution 6 - Java

java.util.Deque has descendingIterator() - if your List is a Deque, you can use that.

Solution 7 - Java

Collections.reverse(nums) ... It actually reverse the order of the elements. Below code should be much appreciated -

List<Integer> nums = new ArrayList<Integer>();
nums.add(61);
nums.add(42);
nums.add(83);
nums.add(94);
nums.add(15);
//Tosort the collections uncomment the below line
//Collections.sort(nums); 

Collections.reverse(nums);

System.out.println(nums);

Output: 15,94,83,42,61

Solution 8 - Java

I know this is an old post but today I was looking for something like this. In the end I wrote the code myself:

private List reverseList(List myList) {
	List invertedList = new ArrayList();
	for (int i = myList.size() - 1; i >= 0; i--) {
		invertedList.add(myList.get(i));
	}
	return invertedList;
}

Not recommended for long Lists, this is not optimized at all. It's kind of an easy solution for controlled scenarios (the Lists I handle have no more than 100 elements).

Hope it helps somebody.

Solution 9 - Java

You can also invert the position when you request an object:

Object obj = list.get(list.size() - 1 - position);

Solution 10 - Java

For small sized list we can create LinkedList and then can make use of descending iterator as:

List<String> stringList = new ArrayList<>(Arrays.asList("One", "Two", "Three"));
stringList.stream().collect(Collectors.toCollection(LinkedList::new))
         .descendingIterator().
         forEachRemaining(System.out::println); // Three, Two, One
System.out.println(stringList); // One, Two, Three

Solution 11 - Java

You can also do this:

static ArrayList<String> reverseReturn(ArrayList<String> alist)
{
   if(alist==null || alist.isEmpty())
   { 
       return null;
   }

   ArrayList<String> rlist = new ArrayList<>(alist);

   Collections.reverse(rlist);
   return rlist;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlbertView Question on Stackoverflow
Solution 1 - JavajcalvertView Answer on Stackoverflow
Solution 2 - JavaColinDView Answer on Stackoverflow
Solution 3 - JavaShakeeb AyazView Answer on Stackoverflow
Solution 4 - JavakkressView Answer on Stackoverflow
Solution 5 - JavaMusefulView Answer on Stackoverflow
Solution 6 - JavaBozhoView Answer on Stackoverflow
Solution 7 - JavaKrishna Kumar ChourasiyaView Answer on Stackoverflow
Solution 8 - JavaCocheLeeView Answer on Stackoverflow
Solution 9 - Javafede1608View Answer on Stackoverflow
Solution 10 - Javaakhil_mittalView Answer on Stackoverflow
Solution 11 - JavajhdrososView Answer on Stackoverflow