RSS

Sorting List in Java

10 Sep

Sorting Lists in Java is a common task. For this Java provides Comparators and Comparables. These are Interfaces which are required to be implemented for sorting purpose. For the demonstration we will consider one at a time. sort method of Collections class in used to sort. This method is overloaded one takes List as its parameter and other takes List and Comparator as its arguments.

Sorting using Comparable Interface:

This Interface has a method compareTo. It compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. In the code provided below the Person class implements Comparable Interface.

package com.sample.beans;

import java.util.Date;

/**
 * @author hgupta
 *
 */
public class Person implements Comparable<Person> {

	/** used for name of the Person **/
	private String name;
	
	/** used for home address of the Person **/
	private String address;
	
	/** used for Date of Birth **/
	private Date dateOfBirth;
	
	/** used for phone number **/
	private Integer phoneNumber;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * @return the dateOfBirth
	 */
	public Date getDateOfBirth() {
		return dateOfBirth;
	}

	/**
	 * @param dateOfBirth the dateOfBirth to set
	 */
	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	/**
	 * @return the phoneNumber
	 */
	public Integer getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber the phoneNumber to set
	 */
	public void setPhoneNumber(Integer phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	@Override
	public int compareTo(Person o) {
		return this.getName().compareTo(o.getName());
	}
	
}

Here the Person class implements the Comparable Interface and so it has the method compareTo. Here in this example it uses String’s compareTo method to compare the String at the base. Depending upon the comparison it returns an int which can be –ve, +ve or 0. Here one concept to be mentioned is it only depends upon the sign of the number but not its magnitude.
Now we will also write a Comparator which will be used to sort the List of Person on the property named dateOfBirth which is of Date type.

package com.comparators;

import java.util.Comparator;

import com.sample.beans.Person;

/**
 * @author Himanshu
 *
 */
public class PersonDOBComparator implements Comparator<Person> {

	@Override
	public int compare(Person o1, Person o2) {
		return o1.getDateOfBirth().compareTo(o2.getDateOfBirth());
	}


}

The PersonDOBComparator implements the Comparator Interface. The method compare takes two arguments and compares them. Using Comparator is easy. If you have any final class whose code cannot be modified, at that stage you can write a comparator. Also if you have a functionality in which you have to sort the List on a number of properties then writing a comparator for each property is easy. Also there are some libraries available which provides comparator on the fly.
Let us sort a List containing Person’s Objects. For this we will make a CollectionSorter.java class which will sort and display the sorted results to the user.

package com.collection.sorting.examples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;

import com.comparators.PersonDOBComparator;
import com.sample.beans.Person;

/**
 * @author hgupta
 *
 */
public class CollectionSorter {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CollectionSorterUtil collectionSorterUtil = new CollectionSorterUtil();
		ArrayList<Person> persons = collectionSorterUtil.getPersonsAsArrayList();
		System.out.println("Orignal List");
		displayPersons(persons);
		Collections.sort(collectionSorterUtil.getPersonsAsArrayList());//Line 1
		System.out.println("List Sorted By Name");
		displayPersons(persons);
		Collections.sort(collectionSorterUtil.getPersonsAsArrayList(), new PersonDOBComparator());// Line 2
		System.out.println("List Sorted By Date of Birth");
		displayPersons(persons);
	}

	private static void displayPersons(ArrayList<Person> persons){
		DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		System.out.println("----------------------------------------------------------");
		for(Person person:persons){
			System.out.print(person.getName());
			System.out.println(" " + dateFormat.format(person.getDateOfBirth()));
		}
		System.out.println("----------------------------------------------------------");
	}
}

This class uses another utility class named CollectionSorterUtil.java which populated the list used by CollectionSorter class. At Line 1 we have used Collections.sort(List list) method to sort the List. It uses the method compareTo which we provided in the Person class by implementing Comparable Interface. At Line 2 we have used a Comparator to sort it. This Comparator uses dateOfBirth to sort the List.

package com.collection.sorting.examples;

import java.util.ArrayList;
import java.util.Date;

import com.sample.beans.Person;

/**
 * @author hgupta
 *
 */
public class CollectionSorterUtil {

	/** ArrayList to store Persons Object**/
	ArrayList<Person> persons = new ArrayList<Person>();
	{
		populatePersons();
	}
	
	/**
	 * This method returns a collection of Person
	 * Objects.
	 * @return {@link ArrayList} Person
	 */
	public  ArrayList<Person> getPersonsAsArrayList(){
		return this.persons ;
	}
	
	private void populatePersons(){
		Person person = new Person();
		person.setName("Mark");
		person.setDateOfBirth(new Date("02/12/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Anthony");
		person.setDateOfBirth(new Date("02/30/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Zulia");
		person.setDateOfBirth(new Date("02/12/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Jenifer");
		person.setDateOfBirth(new Date("05/2/1988"));
		persons.add(person);
		
		person = new Person();
		person.setName("Jhon");
		person.setDateOfBirth(new Date("01/11/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Russels");
		person.setDateOfBirth(new Date("02/12/1980"));
		persons.add(person);
		
		person = new Person();
		person.setName("Erik");
		person.setDateOfBirth(new Date("05/25/1984"));
		persons.add(person);
		
		person = new Person();
		person.setName("Peter");
		person.setDateOfBirth(new Date("12/02/1997"));
		persons.add(person);
		
	}
	
}

After you run the CollectionSorter class you will see the following output in the console.

Orignal List
----------------------------------------------------------
Mark 02/12/1987
Anthony 03/02/1987
Zulia 02/12/1987
Jenifer 05/02/1988
Jhon 01/11/1987
Russels 02/12/1980
Erik 05/25/1984
Peter 12/02/1997
----------------------------------------------------------
List Sorted By Name
----------------------------------------------------------
Anthony 03/02/1987
Erik 05/25/1984
Jenifer 05/02/1988
Jhon 01/11/1987
Mark 02/12/1987
Peter 12/02/1997
Russels 02/12/1980
Zulia 02/12/1987
----------------------------------------------------------
List Sorted By Date of Birth
----------------------------------------------------------
Russels 02/12/1980
Erik 05/25/1984
Jhon 01/11/1987
Mark 02/12/1987
Zulia 02/12/1987
Anthony 03/02/1987
Jenifer 05/02/1988
Peter 12/02/1997
----------------------------------------------------------

About these ads
 
Leave a comment

Posted by on September 10, 2010 in Java, Java Collections

 

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: