- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Reverse a Collection
In this article, we will understand how to reverse a collection. The Collection is a framework that provides architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Below is a demonstration of the same −
Suppose our input is −
Input list:[Java, program, is, fun]
The desired output would be −
The list after reversing is: [fun, is, program, Java]
Algorithm
Step 1 - START Step 2 - Declare a list namely input_list. Step 3 - Define the values. Step 4 - Use the built-in function Collections.reverse() and pass the input_list as parameter to reverse the list. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.*; public class Demo { public static void main(String[] args){ List<String> input_list = new ArrayList<String>(); input_list.add("Java"); input_list.add("program"); input_list.add("is"); input_list.add("fun"); System.out.println("The list is defined as:" + input_list); Collections.reverse(input_list); System.out.println("\nThe list after reversing is: \n" + input_list); } }
Output
The list is defined as:[Java, program, is, fun] The list after reversing is: [fun, is, program, Java]
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.*; public class Demo { static void reverse_list(List<String> input_list){ Collections.reverse(input_list); System.out.println("\nThe list after reversing is: \n" + input_list); } public static void main(String[] args){ List<String> input_list = new ArrayList<String>(); input_list.add("Java"); input_list.add("program"); input_list.add("is"); input_list.add("fun"); System.out.println("The list is defined as:" + input_list); reverse_list(input_list); } }
Output
The list is defined as:[Java, program, is, fun] The list after reversing is: [fun, is, program, Java]
Advertisements