-3

My class is like this:

class Employee{
  int age;
  String name;
  int empId;
  .
  .
  . 
 }

In the main method i have created the object of Employee class and save it in ArrayList say objEmpList. Now,my requirement is to sort objEmpList like the SQL Statemnt as, Select * From Employee Order by age,name,empId; Measn,i want the result sorted by the order of age,name & empId.

For eg: my data is like: 10 Nirdesh 1 10 Ambesh 222 9 Ramesh 9 12 Amar 3

So my result should be,

 9    Ramesh  9
 10   Ambesh  222
 10   Ramesh  1 
 12   Amar    3

How can i achieve this requirement?

Nirdesh
  • 63
  • 2
  • 11

3 Answers3

2

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!

Markus
  • 809
  • 5
  • 10
2

- You can use java.util.Compartor<T> interface if you want to sort on the basis of more than one attribute of the object.

- You will have to use Collections.sort(List<?> l, Comparator c).

Eg:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Car {

    private String name;
    private String brand;
    private double cost;

    public Car(String name, String brand, double cost) {

        this.name = name;
        this.brand = brand;
        this.cost = cost;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getCost() {
        return cost;
    }

    public void setCost(double cost) {
        this.cost = cost;
    }

    public String toString() {

        return getName();
    }

}

public class Hog {

    ArrayList<Car> cars = new ArrayList<Car>();

    public void setIt() {

        cars.add(new Car("Padmini", "Fiat", 100008.00));
        cars.add(new Car("XYlo", "Mahindra", 100000.00));
        cars.add(new Car("Swift", "Maruti", 200000.00));
    }

    public void sortIt() {

        Collections.sort(cars, new NameComparator());
        System.out.println(cars);
        Collections.sort(cars, new BrandComparator());
        System.out.println(cars);
        Collections.sort(cars, new CostComparator());
        System.out.println(cars);
    }

    class NameComparator implements Comparator<Car> {

        public int compare(Car c1, Car c2) {

            return c1.getName().compareTo(c2.getName());
        }
    }

    class BrandComparator implements Comparator<Car> {

        public int compare(Car c1, Car c2) {

            return c1.getBrand().compareTo(c2.getBrand());
        }
    }

    class CostComparator implements Comparator<Car> {

        public int compare(Car c1, Car c2) {

            return new Double(c1.getCost()).compareTo(new Double(c2.getCost()));
        }
    }

    public static void main(String[] args) {

        Hog h = new Hog();

        h.setIt();
        h.sortIt();
    }

}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • This might end up with quite a few Comparators if there are many fields. Also, if you want to order by brand and then by cost, then you're in trouble, right? – Markus Nov 26 '12 at 09:09
  • @Markus, Well never felt the heat of this till now.... and i have been in a project which handles sorting of an object in 8 different ways.... Well the style of programming is quite argumental, i prefer it this way, as till now i have sailed quite flawlessly using this... It would be an honor and quite a learning experience if you can provide me with a better solution, i will be very grateful to you... – Kumar Vivek Mitra Nov 26 '12 at 09:22
0

make Employee implement Comparable, then call Collections.sort(list);

public class Employee implements Comparable<Employee> {

    // rest of class omitted

    public int compareTo(Employee e) {
       // Here's how you order by age, name, empId
       if (age != e.age) return age - e.age;
       if (!name.equal(e.name) return name.compareTo(e.name);
       return empId - e.empId;
    }
}

Then

Collections.sort(list);
Bohemian
  • 412,405
  • 93
  • 575
  • 722