Feb 25, 2011

Sort elements in a collection using Comparable Interface

The Collections class in java provides the following methods for sorting the specified (modifiable) list. This post deals with the first method from the list.

void sort(List list)
void sort(List list, Comparator c)

Key Points

The
sort(List list)
method sorts the elements in ascending order according to the natural ordering of it's elements. The ordering is defined by implementing Comparable interface and overriding the
compareTo()
method. All the elements must implement Comparable interface and must be mutually comparable

Sorting elements using the Comparable Interface

The following example makes use of Person Java Bean to demonstrate the use of Comparable interface and sort in natural order
package com.samples;

//File: Person.java

public class Person implements Comparable<Person>
{
    private String name;
    private int age;

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

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

    public int getAge()
    {
        return age;
    }

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

    /**

     * Provides sorting algorithms with a comparison method for natural ordering
     * of Person elements
     */
    @Override
    public int compareTo(Person p)
    {
        return this.name.compareTo(p.name);
    }
}

package com.samples;

//File: PersonTest.java

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

public class PersonTest
{
    public static void main(String args[])
    {
        Person[] pArray = {
                new Person("Superman", 30),
                new Person("Spiderman", 35),
                new Person("Hitman", 27),
                new Person("Batman", 32),
                new Person("Perry", 10)
        };
        List list = Arrays.asList(pArray);

        DebugPrint(list);
        Collections.sort(list);
        DebugPrint(list);
    }

    private static void DebugPrint(List<Person> list)
    {
        System.out.println();
        System.out.println("== DEBUG ==");
        Iterator<Person> itr = list.iterator();
        while (itr.hasNext())
        {
            Person p = itr.next();
            System.out.println("[Name]: " + p.getName() + "(" + p.getAge() + ")");
        }
    }
}
Output:

No comments :

Post a Comment