Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does anyone know of a Java Comparators library?

I am after a foss library that includes many useful Comparator implementations, that is has lots of little boring comparators that are ready to go.

Apache commons comparators

  • reverse
  • null first/null last
  • chain
  • natural
  • transformer

There are so many other useful reusable possibilities that arent available.

  • whitespace ignoring
  • whitespace normalizing
  • number aware strings - eg "apple 10" > "apple 2".

@SPF Ive included some psuedo code that shows how one can normalize and compare in one pass without creating any temporary strings etc. WHile it is untested and probably doesnt work it wouldnt take much to have a working fast compare.

while {

   while
        get next char from $string1
        if none left then
           $string1 > $string2 return +1;
        get next char from $string1
        increase $index1
        if previous was whitespace and this is whitespace then
           continue;
        end if
   end while

   while
    get next char from $string2
    if none left then
       $string2 > $string1 return +1;
    get next char from $string2
    increase $index2
    if previous was whitespace and this is whitespace then
       continue;
    end if
   end while

   result = $char1 - $char2
   if result != 0 return
}
like image 582
mP. Avatar asked May 21 '11 11:05

mP.


1 Answers

I don't think you'll get many readymade comparators, but Guava has the Ordering class which both extends the Comparator functionality and adds some useful default implementations as factory method

And also: both Guava and Apache Commons / Lang (there: I said it) will help you implement custom Comparators or Comparables using CompareToBuilder and ComparisonChain, respectively. It doesn't get much better than that, I'm afraid.


And about these requirements:

There are so many other useful reusable possibilities that arent available.

  • whitespace ignoring
  • whitespace normalizing
  • number aware strings - eg "apple 10" > "apple 2".

It's not smart to do any of this in a comparator, because it means that your unmodified data remains in the collection and the Comparator need to make the required conversion twice for every comparison. Now think of sorting an Array with several million entries. How many String conversions would that require?

It's always wiser to normalize your data first and then sort it.

like image 177
Sean Patrick Floyd Avatar answered Sep 23 '22 01:09

Sean Patrick Floyd