Home » How to Sort Collections in Java

How to Sort Collections in Java

by Online Tutorials Library

Sorting in Collection

We can sort the elements of:

  1. String objects
  2. Wrapper class objects
  3. User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List. List elements must be of the Comparable type.

Note: String class and Wrapper classes implement the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.

Example to sort string objects

Test it Now

Mukesh Saurav Tahir Viru         

Example to sort string objects in reverse order

Viru Tahir Saurav Mukesh         

Example to sort Wrapper class objects

101 201 230                

Example to sort user-defined class objects

Mukesh Saurav Tahir Viru                

You may also like