Open In App

Java Program to Sort Vector Using Collections.sort() Method

Improve
Improve
Like Article
Like
Save
Share
Report

java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.

Syntax:

Public void sort(Vector object);

Parameters: Instance of the vector as an argument

Illustration: Collection.sort() method

Let us suppose that our list contains
{"Geeks For Geeks", "Friends", "Dear", "Is", "Superb"}

After using Collection.sort(), we obtain a sorted list as
{"Dear", "Friends", "Geeks For Geeks", "Is", "Superb"}
  1. Create a vector instance.
  2. Add elements in the vector.
  3. Printing vector before function using the method to illustrate what the function is responsible for.
  4. Using Collection.sort() method.
  5. Print vector after sorting and it is seen sorting is ascending.

Example 1:

Java




// Java Program to Sort Vector
// using Collections.sort() Method
  
// Importing Collection and Vector class
import java.util.Collections;
import java.util.Vector;
  
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Create a instance vector
        Vector<String> vec = new Vector<String>();
  
        // Insert the values in vector
        vec.add("a");
        vec.add("d");
        vec.add("e");
        vec.add("b");
        vec.add("c");
  
        // Display the vector
        System.out.println("original vector : " + vec);
  
        // Call sort() method
        Collections.sort(vec);
  
        // Display vector after replacing value
        System.out.println("\nsorted vector : " + vec);
    }
}


Output

original vector : [a, d, e, b, c]

sorted vector : [a, b, c, d, e]

Example 2:

Java




// Java Program to Sort Vector
// using Collections.sort() Method
  
// Importing Collection and Vector class
import java.util.Collections;
import java.util.Vector;
  
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Create a instance vector
        Vector<String> vec = new Vector<String>();
  
        // Insert the values in vector
        vec.add("4");
        vec.add("2");
        vec.add("7");
        vec.add("3");
        vec.add("2");
  
        // Display the vector
        System.out.println("\noriginal vector : " + vec);
  
        // Call sort() method
        Collections.sort(vec);
  
        // Display vector after replacing value
        System.out.println("\nsorted vector : " + vec);
    }
}


Output

original vector : [4, 2, 7, 3, 2]

sorted vector : [2, 2, 3, 4, 7]


Last Updated : 11 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads