In this article, we will learn about Java Vector Sort. Vector sort in Java is one of the most used and interesting concepts among many. We will learn step by step with the use of examples. Now first we discuss the definition of Vector sort in java then we will deep dive into explanation with the help of examples. Let’s get started!
What is Java Vector Sort?
The Java Vector Class’s Java Vector Sort function sorts vectors in the order provided by the Comparator. The sort() function in Java is used to arrange the elements in ascending or descending order because Vector maintains the order of insertion of the elements. The Collections class contains the Sort() function, and Comparable and Comparator can also be used to sort vector elements. A vector is a growable object with elements that can be accessed using an integer index, much like an array. After the vector is produced, its size can be altered by adding or removing pieces.
Syntax:
The sort() method is declared using the text below.
public void sort(Comparator super E> c);
The comparator used to compare the vector elements is called mandatory Argument ‘c’. if the method has a return type of void, it returns nothing.
There are no exceptions, and Java 1.2 and later are compatible with this.
Steps to Sort Vector using Comparator
- Creating a Vector object
- Adding elements to Vector using add method(Element e)
- Sorting Vector object using Collections.sort
- Displaying the list of sorted elements
Examples of Java Vector Sort
Here are the examples that are mentioned below.
Example #1
Simple Vector sort() using Collections.sort()
Code:
import java.util.Vector; import java.util.Collections; class SortJavaVectorExample { public static void main(String[] args) { Vector vector = new Vector(); vector.add("10"); vector.add("31"); vector.add("52"); vector.add("23"); vector.add("44"); System.out.println("Vector elements before sorting: "); for(int x=0; x<vector.size(); x++) System.out.println(vector.get(x)); Collections.sort(vector); System.out.println("Sorted Vector elements in ascending order: "); for(int y=0; y<vector.size(); y++) System.out.println(vector.get(y)); } }
Output:
Vector elements before sorting:
10
31
52
23
44
Sorted Vector elements in ascending order:
10
23
31
44
52
The insertion order is preserved when the vector is declared, expanded with elements, and printed with no sorting. Get(x) retrieves an entry from a collection at index x using a for loop. The vector items are sorted using the sort() function, which displays the results using a for loop.
Example #2
Vector sorting for Alphabetical order
Code:
import java.util.*; class VectrSort { public static void main(String arg[]) { Vector < String > v = new Vector < String > (); v.add("Dragon Fruit"); v.add("Apple"); v.add("Watermelon"); v.add("Orange"); v.add("Strawberry"); System.out.println("Elements of Vector are: "); for (String fruit: v) { System.out.println(" "+fruit); } Collections.sort(v); System.out.println("Vector elements after sorting are: "); for (String fruit : v) { System.out.println(" "+fruit); } } }
Output:
Elements of Vector are:
Dragon Fruit
Apple
Watermelon
Orange
Strawberry
Vector elements after sorting are:
Apple
Dragon Fruit
Orange
Strawberry
Watermelon
In order to sort vector elements in descending order, the reverseOrder() function of the Collections class must be used, which by default forces the vector elements to be sorted in reverse order.
Example #3
Sorting Vector Elements in Reverse Order.
Code:
import java.util.Vector; import java.util.Comparator; import java.util.Collections; class reverseSortArray { public static void main(String[] args) { Vector v = new Vector(); v.add("ColorRed"); v.add("ColorYellow"); v.add("ColorBlue"); v.add("ColorBlack"); v.add("ColorOrange"); v.add("ColorGreen"); System.out.println("Vector Elements before sorting :"); for(int x=0; x < v.size(); x++) System.out.println(v.get(x)); Comparator comparator = Collections.reverseOrder(); Collections.sort(v,comparator); System.out.println("Vector Elements after reverse sorting :"); for(int x=0; x < v.size(); x++) System.out.println(v.get(x)); } }
Output:
Vector Elements before sorting :
ColorRed
ColorYellow
ColorBlue
ColorBlack
ColorOrange
ColorGreen
Vector Elements after reverse sorting :
ColorYellow
ColorRed
ColorOrange
ColorGreen
ColorBlue
ColorBlack
As a result, the alphabets are used to sort the vector elements here in decreasing order.
Let’s see how Custom Class Objects’ vector elements are sorted.
The above Collections.sort() method only functions if the elements class implements the Comparable Interface; otherwise, a compilation error will occur.
We’ll see how the special class implements the Comparable Interface in this section.
Example #4
Vector Sorting for Custom Class Objects.
Code:
import java.util.Collections; import java.util.Vector; class Employee implements Comparable<Employee>{ private int empid; public Employee(int empid){ this.empid = empid; } public String toString(){ return "Employee[" + this.empid + "]"; } public int getempId(){ return this.empid; } public int compareTo(Employee otherEmployee) { return this.getempId() - otherEmployee.getempId(); } } class EmployeeSortVector { public static void main(String[] args) { Vector<Employee> vEmp = new Vector<Employee>(); vEmp.add(new Employee(110)); vEmp.add(new Employee(121)); vEmp.add(new Employee(102)); vEmp.add(new Employee(145)); vEmp.add(new Employee(1)); Collections.sort(vEmp); System.out.println(vEmp); } }
Output:
[Employee[1], Employee[102], Employee[110], Employee[121], Employee[145]]
To reverse the order of the following elements, use the reverseComparator.
Collections.sort(vEmp, Collections.reverseOrder())
Using a custom Comparator, we may additionally order objects of a specific class. We already observed the implementation of the Comparable Interface; going forward, we will build a unique comparator for the class objects.
Example #5
Vector Sort of a custom class object using Custom Comparator.
Code:
import java.util.Collections; import java.util.Comparator; import java.util.Vector; class Employee{ private int empid; public Employee(int empid){ this.empid = empid; } public String toString(){ return "Employee[" + this.empid + "]"; } public int getempId(){ return this.empid; } } class EmployeeComparator implements Comparator<Employee>{ public int compare(Employee emp1, Employee emp2) { return emp1.getempId() - emp2.getempId(); } } class EmployeeComparatorDesc implements Comparator<Employee>{ public int compare(Employee emp1, Employee emp2) { return emp2.getempId() - emp1.getempId(); } } class SortJavaVectorExample { public static void main(String[] args) { Vector<Employee> vEmp = new Vector<Employee>(); vEmp.add(new Employee(346)); vEmp.add(new Employee(111)); vEmp.add(new Employee(211)); vEmp.add(new Employee(533)); vEmp.add(new Employee(211)); vEmp.add(new Employee(25)); Collections.sort(vEmp, new EmployeeComparator()); System.out.println(vEmp); Collections.sort(vEmp, new EmployeeComparatorDesc()); System.out.println(vEmp); } }
Output:
[Employee[25], Employee[111], Employee[211], Employee[211], Employee[346], Employee[533]]
[Employee[533], Employee[346], Employee[211], Employee[211], Employee[111], Employee[25]]
Sort Java Vector in Descending Order using Comparator
A growable array of objects is implemented by the Vector class. Although they essentially belong to the legacy classes, vectors are now completely compatible with collections. We may utilize all of the List interface’s methods because it implements the interface and is part of the java.util package.
There are two types of Sorting Technique:
- The first type of sorting is internal, which employs Arrays and the default sorting mechanism of ascending order. For primitive class arrays, wrapper class arrays, and collections, use the sort() function. Both methods of sort() for collections arrange the elements in ascending order.
- The second way is giving a comparator or implementing a comparator interface in the class as the second argument in both methods, and then altering the sorting order to meet the needs. Only arrays of the wrapper class type and collections like vector, ArrayList, etc. are compatible with the comparator.
Input:
vector [4,3,2,6,7]
Output:
vector [2,3,4,6,7]
Approaches to Sort Vector in Descending Order using Comparator:
- Change the items’ default order and implement the comparator interface in the class.
- Call the new comparator directly in the Collections’ second parameter. alter the element’s ordering using the sort() method.
Example 1: by invoking the Collections.sort() function while calling the compare method inside the class that implements the Comparator class, and then constructing and sending the object of that class as a second parameter.
Code:
import java.io.*; import java.util.*; // Implement comparator of the Integer class class PrepBytes implements Comparator<Integer> { // Function to print the elements of the vector static void print(Vector<Integer> Numbers) { for (Integer number : Numbers) { // Printing the elements System.out.print(number + " "); } } public static void main(String[] args) { // Implementing the vector class Vector<Integer> elements = new Vector<>(); // Adding elements in the vector class elements.add(4); elements.add(3); elements.add(2); elements.add(6); elements.add(7); System.out.print("Before sorting elements "); print(elements); System.out.println(); Collections.sort(elements, new PrepBytes()); System.out.print("After sorting elements "); print(elements); } @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }
Output:
Before sorting elements 4 3 2 6 7
After sorting elements 7 6 4 3 2
Example 2: By applying the Collections.sort() method directly, overriding the compare function.
Code:
import java.io.*; import java.util.*; class PrepBytes { // Function to print the elements of the vector static void print(Vector<Integer> Numbers) { for (Integer number : Numbers) { // Printing the elements System.out.print(number + " "); } } public static void main(String[] args) { Vector<Integer> elements = new Vector<>(); elements.add(4); elements.add(3); elements.add(2); elements.add(6); elements.add(7); System.out.print("Before sorting elements "); print(elements); System.out.println(); Collections.sort( elements, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { // Changing the order of the elements return o2 - o1; } }); System.out.print("After sorting elements "); print(elements); } }
Output:
Before sorting elements 4 3 2 6 7
After sorting elements 7 6 4 3 2
Conclusion
We will now wrap up our discussion of "Java Vector Sort." We have seen the definition and usage of Java’s Vector sorting. Its syntax is described together with the necessary arguments. We also covered how vector sorting works and looked at all the many sorts of examples, including using collections.sort() to sort in ascending order and collections.reverseOrder() to sort in descending order. Additionally, we customised the comparable for custom class objects and used Comparable to sort for custom class objects. I believe we have covered all relevant ground. Thanks! Happy studying!