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.


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.


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.


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


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.


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

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

Java 8 Vector Documentation

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping