Java .reverse()
Published Jul 18, 2022
The Collections.reverse() method reverses the current ordering of a List.
Syntax
import java.util.*;
Collections.reverse(myList);
This reverses the ordering of the elements in myList.
Example
The following example creates an ArrayList and then uses Collections.reverse() to reorder the elements:
import java.util.*;public class Main {public static void main(String[] args) {ArrayList<String> food = new ArrayList<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");System.out.println(food);Collections.reverse(food);System.out.println(food);}}
This will output the following:
[Cabbage, Pizza, Sausage, Potatoes, Salad][Salad, Potatoes, Sausage, Pizza, Cabbage]
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours