Languages
[Edit]
EN

Java - iterate through a List in reverse order

0 points
Created by:
Evie-Grace-Noble
351

In this article, we would like to show you how to iterate through a List in reverse order in Java.

 

1. Using reversed for loop

In this example, we use reversed for loop to iterate through the letters ArrayList in reverse order.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> letters = new ArrayList<>();

        letters.add("A");
        letters.add("B");
        letters.add("C");


        for (int i = letters.size(); i-- > 0; ) {
            System.out.println(letters.get(i));
        }
    }
}

Output:

C
B
A

2. Using ListIterator

In this example, we create listIterator and iterate through the letters ArrayList in a while loop using hasPrevious() method.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> letters = new ArrayList<>();

        letters.add("A");
        letters.add("B");
        letters.add("C");

        ListIterator<String> listIterator = letters.listIterator(letters.size());

        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previous());
        }
    }
}

Output:

C
B
A

3. Using Collections.reverse()

In this example, we reverse the letters ArrayList to iterate it backwards.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> letters = new ArrayList<>();

        letters.add("A");
        letters.add("B");
        letters.add("C");

        System.out.println("ArrayList before reverse: " + letters);

        Collections.reverse(letters);

        System.out.println("ArrayList after reverse:  " + letters);

        // iterate over ArrayList
        for (String letter : letters) {
            System.out.println(letter);
        }
    }
}

Output:

ArrayList before reverse: [A, B, C]
ArrayList after reverse:  [C, B, A]

C
B
A
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join