Skip to content

Sort Java Vector Example

This example shows how to sort a Vector in Java. This example also shows how to sort Vector in ascending or descending order using the sort method of the Collections class, Comparable, and Comparator.

How to sort a Vector in Java?

We can sort elements of the vector object using the sort method of the Collection class.

This sort method sorts the specified list elements in their natural order. Since the Vector class has implemented the List interface, we can use this method to sort its elements.

Output

As we can see from the output, the vector elements are sorted in the natural order i.e. ascending order for the type Integer.

How to sort vector elements in descending order?

The overloaded sort method of the Collection class also accepts a Comparator object.

We can pass a Comparator obtain using the reverOrder method of the Collections class to this method to sort the elements in descending order as given below.

Output

How to sort a Vector of custom class objects?

The Collections sort method works only if the list element class has implemented the Comparable interface. If the class has not implemented the Comparable interface, we get a compilation error “The method sort(List<T>) in the type Collections is not applicable for the arguments (Vector<ClassName>)”.

If the Vector elements are objects of a custom class, then the custom class must implement the Comparable interface.

Output

To sort the elements in the descending order, we can pass the Comparator obtained using the Collections reverseComparator method as given below.

Output

How to sort a Vector of custom class objects using the custom Comparator?

Instead of implementing a Comparable interface, we can also create a custom Comparator for the objects of a custom class as given below.

Output

This example is a part of the Java Vector Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Vector Documentation

About the author

Leave a Reply

Your email address will not be published.