java - Sort list on base of multiple criteria -
i sort list on base of multiple criteria.
public class customercomparator implements comparator<customer> { public int compare(customer customer1, customer customer2) { int comparison = -1; comparison = customer2.getcustomerpriority().compareto(customer1.getcustomerpriority()); if( comparison == 0 ) { comparison = customer1.getcustomernumber().compareto(customer2.getcustomernumber()); } return comparison; } }
basically, want sort in following order. customer higher priority should on top of list, , if 2 customers have same priority 1 lower customer number should go first.
original:
customer priority 1 0 2 0 3 1 4 0 5 0
it should sorted below:
customer priority 3 1 1 0 2 0 4 0 5 0
thanks help. dd
java's arrays.sort
, collections.sort
both stable sorting algorithms meaning can sort 1 comparator , another, , values considered equivalent second still ordered first.
it looks you've composed 2 comparator's 1 though, pass the version of sort
takes comparator:
this sort guaranteed stable: equal elements not reordered result of sort.
sorting n different comparators in series,
public static <t> void sort(collection<t> c, comparator<? super t>... cmps) { (comparator<? super t> cmp : cmps) { collections.sort(c, cmp); } }
should functionally equivalent sorting once composition of comparators
public static <t> void sort(collection<t> c, comparator<? super t>... cmps) { collections.sort(c, new comparator<t>() { public int compare(t a, t b) { (int = cmps.length; --i >= 0;) { int delta = cmps[i].compare(a, b); if (delta != 0) { return delta; } } return 0; } }); }
Comments
Post a Comment