Does anyone know of a Java Comparators library?

烈酒焚心 提交于 2019-12-10 15:45:35

问题


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
}

回答1:


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.




回答2:


Commons Lang from 3.0.2 onwards will have a copy of the Collections comparators in the org.apache.commons.lang3.compare package. Feel free to propose more.



来源:https://stackoverflow.com/questions/6081384/does-anyone-know-of-a-java-comparators-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!