Sorting Custom Types in Java

The class java.util.Collections provides many Utility methods for simplifying the most commonly used operations. One of the methods available in that class is sort() which is used for sorting elements. Let us the see how the Collections.sort() method operates on pre-defined data-types as well as user-defined data-types.

also read:

Consider the following code snippet that will sort a list of numbers.

List<integer> numbers = Arrays.asList(1, 5, -4);
Collections.sort(numbers);
System.out.println(numbers);

The method Arrays.asList() creates a new ArrayList object and then populates the list with elements 1, 5 and -4. Then a call is made to Collections.sort() method by passing the collection object. The sort() method directly modifies the collection object after the sorting operation.

What will happen if the Collections.sort() method is passed with a List of user-defined objects? Now, it is the programmer’s responsibility to provide a hint to the sort() method on how sorting has to be done on user-defined objects. Given two user-defined objects o1 and o2, it should be mentioned how to determine whether two objects are equal , whether o1 is greater than o2 or o1 is smaller than o2. So, this can be specified to the Collections.sort() method. There is one more variation of the Collections.sort() that accepts two arguments, one is the list of objects to be sorted and the other is a Comparator object that contains the essential logic for sorting.

Consider the following Movie class, and we want objects of this Movie class to be sorted based on their rank.

Movie.java

package tips.sort;

public class Movie{

    private String name;
    private int rank;

    public Movie(String name, int rank){
        this.name = name;
        this.rank = rank;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getRank() {
        return rank;
    }

    public void setRank(int rank) {
        this.rank = rank;
    }

    public String toString(){
        return name + ':' + rank;
    }
}

Now, let us define the Comparator class that contains the necessary information which in turn can be picked up by the Collections.sort() to perform the sorting operation. Given below is the code for the MovieComparator class,

MovieComparator.java

package tips.sort;

import java.util.Comparator;

public class MovieComparator implements Comparator<movie>{

    @Override
    public int compare(Movie movie1, Movie movie2) {

        int rank1 = movie1.getRank();
        int rank2 = movie2.getRank();

        if (rank1 > rank2){
            return +1;
        }else if (rank1 < rank2){
            return -1;
        }else{
            return 0;
        }
    }
}

Note the use of typed parameter ; in the class declaration of the MovieComparator. Since the actual typed parameter is Movie, the compare() method is made to accept arguments of type Movie. Now, let us see how the implementation is made for the compare() method. For any two movie objects, it checks for their ranks. If the rank for the movie1 is greater than the rank for movie2, then 1 is returned. It means that during the sorting operation movie1 object comes before movie2. If the rank for movie1 is lesser than movie2, then -1 is returned, in which case, movie1 comes after movie2. If the rank for the two objects is equal, then sorting operation does not happen.

The following code makes use of the above classes to perform the sorting operation. Some Movie objects are populated and then passed on to the Collections.sort() method along with the MovieComparator object.

SortingTest.java

package tips.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortingTest {

    public static void main(String[] args) {

        List<movie> movies = new ArrayList<movie>();
        movies.add(new Movie("Harry Potter", 3));
        movies.add(new Movie("Transformer", 4));
        movies.add(new Movie("True Lies", 1));
        movies.add(new Movie("Rush Hour- III", 2));
        movies.add(new Movie("Golden Eye", 5));

        MovieComparator comparator = new MovieComparator();
        Collections.sort(movies, comparator);

        for(Movie aMovie : movies){
            System.out.println(aMovie);
        }
    }
}

The output for the above program is given below,

True Lies:1
Rush Hour- III:2
Harry Potter:3
Transformer:4
Golden Eye:5

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Hi

    Good post. Thanks for sharing.

Trackbacks

  1. [...] to parse a date in Java without knowing the format.” Sort Share http://www.javabeat.net       3 months [...]

Speak Your Mind

*