1 46 package groovy.util; 47 48 import groovy.lang.Closure; 49 50 import java.util.ArrayList ; 51 import java.util.Comparator ; 52 import java.util.Iterator ; 53 import java.util.List ; 54 55 62 public class OrderBy implements Comparator { 63 64 List closures; 65 66 public OrderBy() { 67 this.closures = new ArrayList (); 68 } 69 70 public OrderBy(Closure closure) { 71 this(); 72 closures.add(closure); 73 } 74 75 public OrderBy(List closures) { 76 this.closures = closures; 77 } 78 79 public void add(Closure closure) { 80 closures.add(closure); 81 } 82 83 public int compare(Object object1, Object object2) { 84 for (Iterator iter = closures.iterator(); iter.hasNext();) { 85 Closure closure = (Closure) iter.next(); 86 Object value1 = closure.call(object1); 87 Object value2 = closure.call(object2); 88 89 if (value1 == value2) { 90 continue; 91 } 92 if (value1 == null) { 93 return -1; 94 } 95 if (value1 instanceof Comparable ) { 96 Comparable c1 = (Comparable ) value1; 97 return c1.compareTo(value2); 98 } 99 if (value1.equals(value2)) { 100 continue; 101 } 102 return value1.hashCode() - value2.hashCode(); 103 } 104 return 0; 105 } 106 } 107 | Popular Tags |