Sort list of objects on a field
Suppose you have a list which contains objects of your own class rather than java’s built in classes such as java.lang.Integer, java.lang.String etc. Now you want this list to be sorted on a particular field of this class. Let’s say we have a User class which contains user details such as name, age, address etc., and we have a list of various users.
Now we want a list wherein users are listed in the order of their increasing age. That is, we need to sort the above list in the order of age.
[the_ad id=”651″] Collections.sort method
You can sort a list using sort method of java.util.Collections class. But the question arises that if you pass a list of your own objects to this method, this method does not know the criteria to sort the list. That is, whether it should sort on user name, user age or some other field.
Thus, we need some way to inform sort method about the field on which it should sort the list.
Comparable interface
java.util.Comparable interface defines the method of ordering an object of a class. It defines a way in which the objects should be compared while sorting.
This interface has a compareTo method which compares an object with another object. This method takes an object as argument and returns

    • -1 if the object on which compareTo is called is lesser than the supplied argument,
    • 0 if both the objects are equal, and
    • 1 if the object on which compareTo is called is greater than the supplied object.

If you want to sort a list of objects of a class, then the class should implement java.util.Comparable interface and its compareTo method. This method will define on what basis the objects should be sorted.
Thus, if you want to sort a list of you own User class, then define this class as shown below.

import java.util.Comparable;

//The User class
public class User implements Comparable {
	// age of user. We need to sort on this
	int age;

	// constructor
	public User(int age) {
		this.age = age;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	// Since the class implements Comparable, we need to provide compareTo
	// method implementation
	@Override
	public int compareTo(User o) {
		// return the difference between ages of two users
		return this.age - o.getAge();
	}

}

As you can see, compareTo method compares objects on the basis of age. Below is the code which creates different User objects, add them to a list and then sort is.
[the_ad id=”656″] Note that the program first prints the unsorted list and then the sorted list.

import java.util.Collections;

//main class
public class Sorter {
   public static void main(String[] args) {
	// create a list
	List list = new ArrayList();
	// create users
	User user1 = new User(10);
	User user2 = new User(20);
	User user3 = new User(92);
	User user4 = new User(1);
	// add users to list
	list.add(user1);
	list.add(user2);
	list.add(user3);
	list.add(user4);
	System.out.println("Before Sorting...");
	// iterate over unsorted list
	for (User u : list) {
		// this will print 10,20,92,1. 
                // Since list elements are in the order
		// of insertion
		System.out.println("User age: " + u.getAge());
	}
	// now sort the list
	Collections.sort(list);
	System.out.println("After Sorting...");
	// iterate over sorted list
	for (User u : list) {
		// this prints 1,10,20,92
		System.out.println("User age: " + u.getAge());
	}
   }
}

Above code prints

Before Sorting…
User age: 10
User age: 20
User age: 92
User age: 1
After Sorting…
User age: 1
User age: 10
User age: 20
User age: 92

See! our list is sorted on the basis of age. Similarly, if you want to sort the list of objects on some other field, then modify the compareTo method.
[the_ad id=”647″]
Let’s tweak in

    1. In order to sort the list using sort method of java.util.Collections class, the elements of the list MUST implement java.lang.Comparable interface.
      This is because sort method of java.util.Collections class internally casts the objects to java.lang.Comparable and if the object has not implemented it, a compiler error will be generated, where sort method is being called.
    2. If you declare a class to implement java.lang.Comparable and you do not provide implementation of equals method then a compiler error will be raised.
    3. The signature of the compareTo method in the class implementing java.lang.Comparable should exactly match the signature of compareTo method in Comparable interface, that is, public int compareTo(T o);
      If you change the return type of the method implementation in your class, you will face a compiler error like The return type is incompatible with Comparable.compareTo(User)
    4. Internally sort method of java.util.Collections class converts to an array and this array is then iterated.
      During iteration compareTo method is invoked on all elements of array one by one. One object calls it and object at the next location is passed as an argument to this method as:
      (array[j-1]).compareTo(array[j])
      This is when the compareTo method defined in our class gets called.
    5. compareTo method returns :
      • Negative integer if calling object is lesser than the object passed to it
      • Positive integer if calling object is greater than the object passed to it.
      • Zero if calling object is equal to the object passed to it.

      Object equality is calculated based on the criteria chosen in the compareTo method implementation. In our case, we chose the age but it can be anything such as alphabetical order of user name.

Hope you clearly understood how to sort a list of custom objects using Collections.sort method. Keep visiting!!!

Categorized in:

Java Collection Problems,