Sometimes developers have to realize more complex sorting algorithms. For example you have a list of customers. First you want to sort by age and second by surname. After that you want to sort by forename.
Comparator Implementation:
import java.util.Comparator;
public class CustomerComparator implements Comparator<Customer> {
@Override
public int compare(Customer c1, Customer c2) {
if (c1.getAge() == c2.getAge()) {
if (c1.getSurname().compareTo(c2.getSurname()) == 0) {
return c1.getForename().compareTo(c2.getForename()) {
} else {
return c1.getSurname().compareTo(c2.getSurname());
}
} else if (c1.getAge() > b2.getAge()) {
return -1;
} else {
return 1;
}
}
}
Comparator JUnit Test:
@Test
public void testCustomerComparator() {
Customer customerFirst = new Customer(44,"Alabama", "Christonson");
Customer customerSecond = new Customer(23, "Anna", "Sobek");
Customer customerThird = new Customer(23, "Rafael", "Sobek");
List<Customer> list = new ArrayList<Customer>();
list.add(customerThird);
list.add(customerSecond);
list.add(customerFirst);
//unsorted test
Assert.assertEquals(itemThird, unsortedList.get(0));
Assert.assertEquals(itemSecond, unsortedList.get(1));
Assert.assertEquals(itemFirst, unsortedList.get(2));
Comparator<Customer> customerComparator = new CustomerComparator();
Collections.sort(list, customerComparator);
//sorted test
Assert.assertEquals(customerFirst, list.get(0));
Assert.assertEquals(customerSecond, list.get(1));
Assert.assertEquals(customerThird, list.get(2));
}
Regards
Rafael Sobek
Technorati Tags: Comparator java sorting

Complex Sorting with Java Comparator
Sometimes developers have to realize more complex sorting algorithms. For example you have a list of customers. First you want t...... [full post]