saic_gco
asked on
Sorting list of objects based on child object members
Here is a simple version of my problem, consider the following 2 classes. Given a list of Car objects, I would like to sort first by Category name, then by Car name. Is there anything in the api that can help with this task? Or what sort algorithm would be best consider the Lists I'm working with would not exceed 1000 entries. Thank you.
public Car {
public String name;
public Category cat;
.....
}
public Category {
public String name;
....
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
hey objects,
it not Collection.sort
it is Collections.sort :)))
it not Collection.sort
it is Collections.sort :)))
ASKER
objects.complimentStringVe ctor.add(" you da man");
Collection.sort(cars, new Comparator()
{
public int compare(Object a, Object b)
{
Car car1 = (Car) a;
Car car2 = (Car) b;
return car1.getName().compareTo(c
}
});
System.out.println(cars);
// by category
Collection.sort(cars, new Comparator()
{
public int compare(Object a, Object b)
{
Car car1 = (Car) a;
Car car2 = (Car) b;
return car1.getCatgory().getName(
}
});
System.out.println(cars);