I am wondering if there are some kind of reverse_iterator(like c++) in List implementation like ArrayList<Integer>
. i.e, I would like to iterate from the end of the List rather than from the beginning?
Is there any Java8 stream solution?
I am wondering if there are some kind of reverse_iterator(like c++) in List implementation like ArrayList<Integer>
. i.e, I would like to iterate from the end of the List rather than from the beginning?
Is there any Java8 stream solution?
In java there is List Iterator https://www.journaldev.com/13457/java-listiterator
// Substitute appropriate type.
ArrayList<...> a = new ArrayList<...>();
// Add elements to list.
// Generate an iterator. Start just after the last element.
ListIterator li = a.listIterator(a.size());
// Iterate in reverse.
while(li.hasPrevious()) {
System.out.println(li.previous());
}
Another way you could have reversed the list is to use Collections.reverse
ArrayList<Integer> a = new ArrayList<>(); // assign some values here
a.forEach(System.out::println); // actual order
Collections.reverse(a);
a.forEach(System.out::println); // reverse order
Yes there is a option for reverse iteration in java.Below code works fine.
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(2);
al.add(3);
al.add(4);
ListIterator<Integer> itr = al.listIterator(al.size());
System.out.println("Printing from last element ");
while (itr.hasPrevious()) {
System.out.println(itr.previous());
}