Java Program to Sort Vector Using Collections.sort() Method
Last Updated :
11 Dec, 2020
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"}
- Create a vector instance.
- Add elements in the vector.
- Printing vector before function using the method to illustrate what the function is responsible for.
- Using Collection.sort() method.
- Print vector after sorting and it is seen sorting is ascending.
Example 1:
Java
import java.util.Collections;
import java.util.Vector;
public class GFG {
public static void main(String args[])
{
Vector<String> vec = new Vector<String>();
vec.add( "a" );
vec.add( "d" );
vec.add( "e" );
vec.add( "b" );
vec.add( "c" );
System.out.println( "original vector : " + vec);
Collections.sort(vec);
System.out.println( "\nsorted vector : " + vec);
}
}
|
Output
original vector : [a, d, e, b, c]
sorted vector : [a, b, c, d, e]
Example 2:
Java
import java.util.Collections;
import java.util.Vector;
public class GFG {
public static void main(String args[])
{
Vector<String> vec = new Vector<String>();
vec.add( "4" );
vec.add( "2" );
vec.add( "7" );
vec.add( "3" );
vec.add( "2" );
System.out.println( "\noriginal vector : " + vec);
Collections.sort(vec);
System.out.println( "\nsorted vector : " + vec);
}
}
|
Output
original vector : [4, 2, 7, 3, 2]
sorted vector : [2, 2, 3, 4, 7]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...