quinta-feira, 14 de janeiro de 2010

MultiComparator

Quando você escreve um SQL para retornar informações do banco de dados de forma ordenada por vários campos, você escreve algo mais ou menos assim:

ORDER BY nome, idade, codigo

E em Java como você reproduz esta funcionaliade?

Eu faço assim ó :D





/**
* You can easily combine the results from several Comparators for an object
* class into one Comparator.
*


*
* You have the multi-comparator, and individual comparators for all the fields,
* you can create a comparator that has any properties you want. For example, to
* sort on EmployeeID, Name, and Age, in that order, you would do this:
*


*
*


* MultiComparator mc = new MultiComparator();
* mc.add(new EmployeeIdComparator(MyENum.ASC));
* mc.add(new EmployeeNameComparator(MyENum.ASC));
* mc.add(new EmployeeAgeComparator(MyENum.DESC));
* Collections.sort(list, mc);
*

*/
public class MultiComparator implements Comparator < book > {
private List<comparator < book > comparatorList;

public MultiComparator() {
comparatorList = new ArrayList<comparator<book>>();
}

public void addComparator(Comparator<book> c) {
comparatorList.add(c);
}

public void removeComparator(Comparator<object> c) {
comparatorList.remove(c);
}

public int compare(Book obj1, Book obj2) {
int result = 0;
for (Comparator<book> c : comparatorList) {
result = c.compare(obj1, obj2);

if (result != 0) {
break;
}
}
return result;
}
}