Does anyone know the Java Comparators library?

I am after the foss library, which includes many useful Comparator implementations that have many small boring comparators that are ready to go.

Apache Comparators

  • the opposite
  • null first / null last
  • chain
  • natural
  • transformer

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

  • ignoring spaces
  • gap normalization
  • lines with numbers - for example, "apple 10"> "apple 2".

@SPF Ive included some psuedo code that shows how you can normalize and compare in a single pass without creating timelines, etc. If this is unverified and probably doesn't work, it won't take a lot of effort to quickly 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 } 
+4
java comparator
source share
2 answers

I don’t think you will get many ready-made comparators, but Guava has Ordering , which extends the functionality of Comparator and adds some useful default implementations as a factory method

And also: Guava and Apache Commons / Lang (there: I said that) will help you implement custom comparators or comparative examples using CompareToBuilder and ComparisonChain , respectively. I'm afraid this is not much better.


And about these requirements:

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

  • ignoring spaces
  • gap normalization
  • lines with numbers - for example, "apple 10"> "apple 2".

It is not recommended to do this in the comparator, because this means that your unchanged data remains in the collection, and Comparator needs to do the required conversion twice for each comparison. Now think about sorting an array with several million records. How many string conversions will it take?

It is always wiser to normalize your data first and then sort them.

+5
source share

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

+1
source share

All Articles