Java Program to Reverse a Collection

JavaCampus InterviewServer Side ProgrammingProgramming

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("
The list after reversing is:
" + 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("
The list after reversing is:
" + 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]
raja
Updated on 30-Mar-2022 06:37:29

Advertisements