Link to home
Start Free TrialLog in
Avatar of saic_gco
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;
  ....
}

Open in new window

Avatar of Mick Barry
Mick Barry
Flag of Australia image

// by name

Collection.sort(cars, new Comparator()
{
   public int compare(Object a, Object b)
   {
       Car car1 = (Car) a;
       Car car2 = (Car) b;
       return car1.getName().compareTo(car2.getName());
   }
});
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().compareTo(car2.getCategory().getName());
   }
});
System.out.println(cars);
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hey objects,
it not Collection.sort
it is    Collections.sort  :)))
 
Avatar of saic_gco
saic_gco

ASKER

objects.complimentStringVector.add("you da man");