1

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?

Naman
  • 21,685
  • 24
  • 196
  • 332
Adam Lee
  • 23,314
  • 47
  • 144
  • 221

3 Answers3

6

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());
}
Amit Kumar Lal
  • 5,013
  • 3
  • 18
  • 36
  • Although your answer is correct, I would like to see if there is some elegant Java8 solution:-) let's wait for some more time – Adam Lee Oct 28 '18 at 09:31
1

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
Naman
  • 21,685
  • 24
  • 196
  • 332
0

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());
}
Abdullah Al Mamun
  • 341
  • 2
  • 4
  • 15