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
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
java.util.Deque
has descendingIterator()
- if your List
is a Deque
, you can use that.
Use reverse(...)
methods of java.util.Collections
class. Pass your list as a parameter and your list will get reversed.
Collections.reverse(list);
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.
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);
You can also invert the position when you request an object:
Object obj = list.get(list.size() - 1 - position);