You should implement a new class EmployeeComparator that implements Comparator. Configure the order of fields by specifying a vararg list of field names public EmployeeComparator(String... fields)
.
Here is an example:
public class CarComparator implements Comparator<Car> {
private final List<String> fieldSortOrder;
public CarComparator(String... fieldSortOrder) {
this.fieldSortOrder = new ArrayList<String>(
Arrays.asList(fieldSortOrder));
}
@Override
public int compare(Car a, Car b) {
try {
return cmp(a, b, fieldSortOrder);
} catch (Exception e) {
return 0;
}
}
private int cmp(Car a, Car b, final List<String> fields) throws Exception {
if (fields.isEmpty())
return 0;
PropertyDescriptor pd = new PropertyDescriptor(fields.get(0), Car.class);
String ma = (String) pd.getReadMethod().invoke(a);
String mb = (String) pd.getReadMethod().invoke(b);
if (ma.compareTo(mb) == 0) {
return cmp(a, b, fields.subList(1, fields.size()));
} else {
return ma.compareTo(mb);
}
}
}
Then have the list sorted like this:
Collection.sort(cars, new CarComparator("brand", "mileage"));
You will need accessors (i.e. getters and setters) for each field in your value object, and the example above will have a bit of trouble with non-string fields. But I guess I should leave some of the fun to you! :)
Good luck!