2

I was wondering if there was a way to reverse traverse a Iterable in Java.

Iterable<DataSnapshot> snapShotIterator = dataSnapshot.getChildren();

for (DataSnapshot doc : snapShotIterator) {
    BlogPost blogPost = doc.getValue(BlogPost.class);
    blog_list.add(blogPost);
}

Above is my code that I am trying to get to traverse in a reverse order, is there a reverse function for Iterables like there is for Collections?

Thanks in advance!

Hyungjun

MohanKumar
  • 960
  • 10
  • 26
Hyungjun
  • 65
  • 7
  • 1
    you may check accepted answer here https://stackoverflow.com/questions/1098117/can-one-do-a-for-each-loop-in-java-in-reverse-order – Zain Oct 05 '19 at 04:56

2 Answers2

2

You can use Android Studio replace with "For Loop" and then "Reverse it"

        ArrayList<String> list = new ArrayList<>();

        list.add("Hello");
        list.add("World");

        // Iterate forwards
        for (String string : list) {
            //
        }

this is a normal iteration.

Now if you position yourself on top of the for statement and do alt-enter (on Linux/Windows, can't remember the macOS shortcut)... you get:

for

And then, if you do it again (alt-enter), you now get the option to reverse the loop:

reversed

Which looks like this:

        for (int i = list.size() - 1; i >= 0; i--) {
            String string = list.get(i);
        }

Obviously, this doesn't consider you having an "Iterator" but you get the idea in case you want to iterate over collections directly, without resorting to the Iterator interface.

Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144
  • You should accomodate the answer to the question use case, can you add a line using iterator get at index? – cutiko Oct 05 '19 at 12:18
1

basically you can reverse the iterable by traversing it and storing it's value in a reverse list, then traverse that list,

you'll have to traverse the iterable at first to be able to do iterate in reverse order

you can use org.apache.commons.collections.iterators to do it without implementing yourself

ReverseListIterator reverseListIterator = new ReverseListIterator(list);

of course there are a lot of other libs you can use

more can be found here

shahaf
  • 4,750
  • 2
  • 29
  • 32