Sorting User-defined data structures using the Comparator Interface

If you want to sort a set of objects using a particular logic, you can do so without having to implement the sorting algorithm. Java2 provides an interface that you can implement to provide the sorting algorithm the logic to compare two objects of any arbitrary object, or even different objects.

The interface is called Comparator. The advantage of using this interface is that it is possible to define a comparator for any kind of data object. One could theoretically write a comparator implementation for comparing Strings with Integers.

In the following example, a custom data structure class, DataClass is present. The class itself provides an implementation of the Comparator interface so that a collection of DataClass objects can be sorted. The example firsts creates a few DataClass objects and then sorts them using Arrays.sort.

It is possible to use a data structure other than a linked list to store the DataClass objects so that the iterator that provides the elements itself provides them in sorted order. Please refer our other examples on collections.

Code

/*
 * This example is from javareference.com
 * for more information visit,
 * http://www.javareference.com
 */

//package

//import statements
import java.util.*;
/*
 * @author Anand Hariharan([email protected])
 *
 */
public class Compare
{
    public static void main(String[] args)
    {
        DataClass d1 = new DataClass();
        d1.i = 10;
        d1.j = 0.75F;

        DataClass d2 = new DataClass();
        d2.i = 7;
        d2.j = 0.23F;

        DataClass d3 = new DataClass();
        d3.i = 12;
        d3.j = 1.55F;

        DataClass d4 = new DataClass();
        d4.i = 4;
        d4.j = 0.92F;

        DataClass d5 = new DataClass();
        d5.i = 4;
        d5.j = 0.34F;

        LinkedList l = new LinkedList();
        l.add(d1);
        l.add(d2);
        l.add(d3);
        l.add(d4);
        l.add(d5);

        ListIterator li = l.listIterator();

        System.out.println("Input Data...");

        while(li.hasNext())
        {
            System.out.println(li.next());
        }

        Object [] listArray = l.toArray();
        Arrays.sort(listArray, d1);

        System.out.println("");
        System.out.println("Sorted Array...");

        for(int i=0; i; i++)
        {
            System.out.println(listArray[i]);
        }
    }

    static class DataClass implements Comparator
    {
        int i;
        float j;

        public String toString()
        {
            return i + ", " + j;
        }

        /*
         * The compare method that compares two objects of type DataClass.
         * The logic is : i takes precedence over j. If obj1.i is greater or
         * lesser than obj2.i, then obj1 is greater or lesser (respectively)
         * than obj2. In the event that obj1.i and obj2.i are the same, then
         * the same comparison is carried out using j.
         */
        public int compare(Object p1, Object p2)
        {
            if((p1 instanceof DataClass) &&
                    (p2 instanceof DataClass))
            {
                DataClass d1 = (DataClass) p1;
                DataClass d2 = (DataClass) p2;

                // Logic to check which of the objects is
                // greater. In this case, if i is greater
                // then the object is greater, irrespective
                // of the value of j. Only if value of i is
                // equal, then the test is carried out for j.

                if(d1.i < d2.i)
                {
                    return -1;
                }
                else if(d1.i > d2.i)
                {
                    return 1;
                }
                else
                {
                    if(d1.j < d2.j)
                    {
                        return -1;
                    }
                    else if(d1.j > d2.j)
                    {
                        return 1;
                    }
                }
            }

            return 0;
        }

        /*
         * Checks equality of DataClass objects
         */
        public boolean equals(Object p1)
        {
            if(p1 instanceof DataClass)
            {
                DataClass d1 = (DataClass) p1;

                // If both i and j are equal, return true.
                if((d1.i == i) &amp;&amp; (d1.j == j))
                {
                    return true;
                }
            }

            return false;
        }

    }
}
0

Leave a Reply