I’m using Java Comparator for sorting in my code. How I can only sort by certain values, e.g., the values range from 1 to 1000, (default is 1000), but I only want ascending sort to show 1,2,3,4,5,1000…, and descending sort to show 5,4,3,2,1,1000….
How do I do this?
Thanks,
David
The comparators below treat the value 1000 as always “greater” than everything else; 1000 will always sort last. Any other values are sorted either ascending or descending.
Edit:
This is not a general solution, but answers the specific question. In a general solution you must pay attention to the contract of
equals()andcompare(), especially being sure not to return inconsistent comparison results. For example, if you’re not careful and accidentally return, say +1 forcompare(a,b)andcompare(b,a)then the sort could get into an infinite loop.