Saturday, April 5, 2008

Sorting using Collection provided methods


Basic sorting of a collection of String objects


Create a sample list of Strings



List nameList = new ArrayList( );
/* Adding data to arraylist */

nameList.add("John");
nameList.add("Adam");
nameList.add("Susan");
nameList.add("Susan");
nameList.add("Susan");
nameList.add("Rick");

Sort it using sort() method provided by Collections



Collections.sort(nameList);

Sorting of a collection of user defined objects say ‘Person’


Create a collection of Person objects



List personList = new ArrayList();

/* Adding Person objects to arraylist */

personList.add(new Person("John",23));
personList.add(new Person("Adam",24));
personList.add(new Person("Susan",22));
personList.add(new Person("Susan",18));
personList.add(new Person("Susan",15));
personList.add(new Person("Rick",30));




class Person {
public Person(String name,int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName( ) {
return this.name;
}
public int getAge() {
return this.age;
}
}

Create a Comparator to define the rule (i.e.., based on which ‘Person’s property, collection is to be sorted)Creating a separate class that implements Comparator



class CompareObjects implements Comparator {
public int compare(Object object1, Object object2) {
/* Casting objects from Collection to Person */

Person a = (Person) object1;
Person b = (Person) object2;

/* Getting Collator instance using java.text.Collator
since we are performing an alphabeticalcomparison instead of normal String comparison */


Collator collator = Collator.getInstance( );
int result = collator.compare(a.getName( ),b.getName( ));
return result;
}
}

Sort using the overloaded sort() method provided by Collections



Collections.sort(personList,new CompareObjects( ));

We can also create an anonymous inner class for Comparator and pass it to Collection’s sort method



Collections.sort(personList, new Comparator( ) {
public int compare(Object object1, Object object2) {
/* Method body same as given above */
}
});

Complex Sorting


Consider the scenario: All Person objects has to be sorted based on their ‘name’ first and if two persons have same name, they have to be again sorted based on their ages.
For this case, we can re-write our comparator as below



class CompareObjects implements Comparator {
public int compare(Object object1, Object object2) {
/* Casting objects from Collection to Person */
Person a = (Person) object1;
Person b = (Person) object2;
/* Getting Collator instance using java.text.Collator
since we are performing an alphabeticalcomparison instead of normal String comparison */

Collator collator = Collator.getInstance( );
int result = collator.compare(a.getName( ),b.getName( ));
/* When the result is 0, it means that two persons
with same name */

if(result == 0) {
if(a.getAge( ) < b.getAge( ))
result = -1;
else
result = 1;
}
return result;
}
}

No comments: