How to sort JAVA collection elements (part 2)

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
How to sort JAVA collection elements

Probably you've worked with List in a moment of your JAVA developer life, and we can say that using a List instead an array is more beautiful because the list grows automatically, you can add elements easily (only objects, but if you want to add primitives use wrapper classes) and so on. But, How to sort the elements of a list?
Suppose that you have a list of employees. Those employees have the next data:
complete name age sex position
So, you have your JAVA bean Employeee, like this: (Continue reading the post)







