java

How to iterate a list in reverse order in Java

To iterate a list in reverse order, there is a simple method: for loop that counts from list.size() - 1 to 0 and selects the respective element with list.get(i). But there is also a possibility with an iterator.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More

 
Similar to the well-known iterator, there is also a listIterator() method in the List interface that returns a ListIterator. This contains possibilities to iterate the list in both directions and to change it.

import java.util.*;

public class Main
{
    public static void main(String[] args) 
    {
        List<String> names = new ArrayList<>(Arrays.asList("Alex", "Thomas", "Emily", "Bob", "Jean"));
        
        ListIterator<String> listIterator = names.listIterator(names.size());
        
        while(listIterator.hasPrevious()) 
        {
            System.out.println(listIterator.previous());
        }
    }
}

This example produces the following output:

Jean
Bob
Emily
Thomas
Alex

Of course, you could also simply reverse the order of the list, but this would change the original list.
How to reverse a list in JavaHow to reverse a list in JavaIn this tutorial, we’re going to see how we can reverse the elements of a list in Java. If the list can be changed, Java…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *