-1

Possible Duplicate:
Sorting Java objects using multiple keys

I have an employee class. Based on the employee name I want to sort. If the employee names for two objects (i.e. two employees) are same then I want to sort it with respect to the employee age.

For sorting w.r.t the employee name, I implemented the COmparable interface and used this code:

@Override
public int compareTo(Employee o) {
    return name.compareTo(o.getName());
}

This bit of code is working fine for me. But I am not able to understand how to incorporate the sorting based on age when the name of two employee are same?

Do i need to use the Comparator for this? I am not sure how to achieve this.

Please help

Community
  • 1
  • 1
user182944
  • 7,897
  • 33
  • 108
  • 174

3 Answers3

1

If the names are the same (ie a result of 0) then you can then sort by age. If the names return a non zero result then just return that

for example

@Override
public int compareTo(Employee o) {
    int i = name.compareTo(o.getName());
    if (i == 0) { //ie the names are the same
        return age.compareTo(o.getAge();
    }
    return i;
}
RNJ
  • 15,272
  • 18
  • 86
  • 131
0

You can store the employees into an ArrayList, then can sort them using Collections.sort

public class CustomComparator implements Comparator<Employee> {
    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getAge().compareTo(o2.getAge());
    }
}

Now you can use the Collections.sort as below:

Collections.sort(employeeList, new CustomComparator());
tokhi
  • 21,044
  • 23
  • 95
  • 105
  • -1 this does not take into account the names of the employee? The questions says to only sort by age if the names are the same – RNJ Dec 08 '12 at 14:39
-1

The logic in your description should directly translate into your code:

public int compareTo(Employee o)
{
    firstfield = name.compareTo(o.name())
    if( firstfield == 0 )
    {
        return age.compareTo(o.age())
    }
    else
    {
        return firstfield
    }
}

You can also do the work by constructing new strings to compare:

public int compareTo(Employee o)
{
    me = sprintf( "%s:%d", name, age)
    them = sprintf( "%s:%d", o.name, o.age )
    return me.compareTo(them)
}
David Paigen
  • 123
  • 2
  • The second way of doing is awful, and doesn't work. The first way of doing has already been given as an answer by RNJ, except his answer compile fine, whereas yours doesn't. – JB Nizet Dec 08 '12 at 14:33