Here we will learn how to sort elements of Vector in descending order with comparator and reverseOrder method of Collections class.
Source Code
1)
package com.beginner.examples;
import java.util.Collections;
import java.util.Vector;
public class SortOfVectorExample {
public static void main(String[] args) {
Vector vector = new Vector();
//Add elements
vector.add(5);
vector.add(6);
vector.add(3);
vector.add(1);
vector.add(7);
System.out.println("unsorted:"+vector);
/*
* Use the sort() method in the Collections class to sort
* Use a method with one argument,
* The object stored in the vector must implement the Comparable interface
* The Integer type added here already implements the Comparable interface
*/
Collections.sort(vector);
System.out.println("After the sorting:"+vector);
}
}
Output:
unsorted:[5, 6, 3, 1, 7]
After the sorting:[1, 3, 5, 6, 7]
2.Custom comparator class)
package com.beginner.examples;
import java.util.Comparator;
public class MyComparator implements Comparator
{
@Override
public int compare(Integer o1, Integer o2) {
int result =o2-o1;
return result;
}
}
3)
package com.beginner.examples;
import java.util.Collections;
import java.util.Vector;
public class SortOfVectorExample2 {
/**
* Custom comparator
*/
public static void main(String[] args) {
Vector vector = new Vector();
// Add elements
vector.add(5);
vector.add(6);
vector.add(3);
vector.add(1);
vector.add(7);
System.out.println("unsorted:" + vector);
/*
* When you make a custom comparison, you need to pass in a comparator
* Mycomparator is a custom comparator
*/
Collections.sort(vector, new MyComparator());
System.out.println("After the sorting:" + vector);
}
}
Output:
unsorted:[5, 6, 3, 1, 7]
After the sorting:[7, 6, 5, 3, 1]
References
Imported packages in Java documentation: