java

How to reverse a list in Java

In 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 offers a simple method in the class java.util.Collections. For example, if we have this list:

List: 1 2 3 4 5 6 7 8 9 10

In the result we can have:

List: 10 9 8 7 6 5 4 3 2 1

 

Reverse the list itself

If the list itself may be changed, reversing the order with the method Collections.reverse() can be very easy:

import java.util.*;

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

Output:

[Jean, Bob, Emily, Thomas, Alex]
 
If you don’t want the original list to be changed, see the example below.
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
Insert elements into new list in reverse order

If you do not want to change the original list or if it is unchangeable, simply create a new list with the same size. The naive simple solution could look like this:

import java.util.*;

public class Main
{
    public static void main(String[] args) 
    {
        List<String> names = new ArrayList<>(Arrays.asList("Alex", "Thomas", "Emily", "Bob", "Jean"));
        
        List<String> inverse = new ArrayList<>(names.size());
        
        for (int i = names.size()-1; i >= 0; i--) 
        {
            inverse.add(names.get(i));
        }
        
        System.out.println(inverse);
    }
}

Output:

[Jean, Bob, Emily, Thomas, Alex]
How to iterate a list in reverse order in JavaHow to iterate a list in reverse order in JavaTo iterate a list in reverse order, there is a simple method: for loop that counts from list.size() - 1 to 0 and selects the…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 *