JAVA How to JAVA Development tutorials and how to

1Mar/100

How to sort JAVA collection elements (part 2)

JAVA List Comparator ordering - JAVA How to
Continuing with "How to sort JAVA collection elements", i want to share with you another way to sort collections that have it's differences to the first way (using Comparable interface) and enables you to have different sort options, i'm talking about use the Comparator interface.

class Employee implements Comparable<Employee> {
	private String completeName;
	private int age;
	private boolean sex;
	private String position;

	public Employee(String completeName, int age, boolean sex, String position) {
			setCompleteName(completeName);
			setAge(age);
			setSex(sex);
			setPosition(position);
	}

	@Override
	public String toString()
	{
		return getCompleteName() + ", " + getAge() + " years, " +
				(isSex()?"male, ":"female, ") + getPosition();
	}

	public String getCompleteName() {
		return completeName;
	}

	public void setCompleteName(String completeName) {
		this.completeName = completeName;
	}

	public int getAge() {
		return age;
	}

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

	public boolean isSex() {
		return sex;
	}

	public void setSex(boolean sex) {
		this.sex = sex;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

	public int compareTo(Employee o) {
		return getCompleteName().compareTo(o.getCompleteName());
	}
}

Wait... Comparable and Comparator? Yes, you read well. The comparator interface is slightly similar to comparable, because it defines a method called compare() that works like compareTo() of Comparable interface, but it has the difference that you don't need to implement Comparator in the collection's class type. To explain that a little bit well, i'm going to resume the example of the last post. I have my Employee class implementing Comparable interface and it's method compareTo() that orders in ascending order based on completeName field (if you haven't read the first post you can download the sample code >>HERE<<).

Now, additional to it, i wan to have the option of order an Employee list based on age field descending or position ascending. How to do that in JAVA?? Continue reading :D

To do that, we have to write 2 classes that implements Comparator interface, implements the compare() method to specify the 2 sorting choices that we want to have. After coding, we have our 2 classes like this (By de way, don't forget the import to Comparator):

	class OrderEmpAgeDesc implements Comparator<Employee> {
		public int compare(Employee o1, Employee o2) {
			return -1 * ((new Integer(o1.getAge())).compareTo(new Integer(o2.getAge())));
		}
	}

	class OrderEmpPositionAsc implements Comparator<Employee> {
		public int compare(Employee o1, Employee o2) {
			return o1.getPosition().compareTo(o2.getPosition());
		}
	}

As you can see, Comparator interface also is generic (like Comparable) so we can specify the Employee type to avoid to write code to verify class type and class cast. The first class, used to order by age descending, we use wrapper classes because them provides compareTo() method, and we multiply the result by -1 because the natural order is ascending and we want to order descending. In the second class, to order by position ascending is more simple because it looks ike compareTo() method of Employee, with the difference that compares the position field instead completeName field.

Finally, how to use these new classes? If you saw in detail the methods of Collections, you could see two implementations of sort() : one that receives the collection that you want to sort and another that receives the collection that you wan to sort AND a Comparator object to use the sorting logic inside compare() method implementation. so, let's going to modify a little bit our main class (if you haven't read the first post, you can access >>HERE<< to read it and have the source code example) to sort our Employee list using the two classes that we created:

	List<Employee> ourEmployeesList = new ArrayList<Employee>();
	ourEmployeesList.add(new Employee("John Connor", 34, true, "Fighter against Terminators"));
	ourEmployeesList.add(new Employee("Oscar Calderon", 22, true, "Developer"));
	ourEmployeesList.add(new Employee("Scarlett Johansson", 28, false, "Actress"));
	ourEmployeesList.add(new Employee("Zandrox Ubliq", 67, false, "I dont know"));
	//Order our list?
	Collections.sort(ourEmployeesList);
	//Iterate through the list
	for(Employee tmpEmp : ourEmployeesList)
	{
		System.out.println(tmpEmp.toString());
	}
	System.out.println("------------------ Order our list by age descending");
	Collections.sort(ourEmployeesList, new OrderEmpAgeDesc());
	//Iterate through the list
	for(Employee tmpEmp : ourEmployeesList)
	{
		System.out.println(tmpEmp.toString());
	}
	System.out.println("------------------ Order our list by position ascending");
	Collections.sort(ourEmployeesList, new OrderEmpPositionAsc());
	//Iterate through the list
	for(Employee tmpEmp : ourEmployeesList)
	{
		System.out.println(tmpEmp.toString());
	}

You will get the next output:

John Connor, 34 years, male, Fighter against Terminators
Oscar Calderon, 22 years, male, Developer
Scarlett Johansson, 28 years, female, Actress
Zandrox Ubliq, 67 years, female, I dont know
------------------ Order our list by age descending
Zandrox Ubliq, 67 years, female, I dont know
John Connor, 34 years, male, Fighter against Terminators
Scarlett Johansson, 28 years, female, Actress
Oscar Calderon, 22 years, male, Developer
------------------ Order our list by position ascending
Scarlett Johansson, 28 years, female, Actress
Oscar Calderon, 22 years, male, Developer
John Connor, 34 years, male, Fighter against Terminators
Zandrox Ubliq, 67 years, female, I dont know

As you can see, ordering your lists using Comparable or Comparator has advantages and disadvantages. In the Comparable's side, the advantage is that you only have to implement the interface in the list class and implement the method, and the disadvantage is that you're restricted to only 1 sorting option. With Comparator you have the advantage that you can have multiple sorting options, additional to the fact that you can use your Comparator implementations to sort different types of list if you play well with inheritance with your list types, but the disadvantage is that you must create a class for each sorting option that you want (you can see this as annoying or it doesn't matter for you ) but in the end, you have the choice :P .

I hope that this will be useful for you, and you can download the entire source code of this post >>HERE<< .

import java.lang.Integer;
class OrderEmpAgeDesc implements Comparator<Employee> {
public int compare(Employee o1, Employee o2) {
return -1 * ((new Integer(o1.getAge())).compareTo(new Integer(o2.getAge())));
}
}

class OrderEmpPositionDesc implements Comparator<Employee> {
public int compare(Employee o1, Employee o2) {
return o1.getPosition().compareTo(o2.getPosition());
}
}

Share and Enjoy

  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • Technorati
  • MySpace
  • Sphinn
  • Print
  • Mixx
  • Google Bookmarks
  • Blogplay
  • Identi.ca
  • LinkedIn
  • Meneame
  • Netvibes
  • Yigg
  • Reddit
  • RSS
  • Tumblr
Comments (0) Trackbacks (1)

Leave a comment