8

Is there a Comparator implementation in Guava to sort strings in a "natural" way that may contain numbers?
Eg:
"a 8"
"a 9"
"a 10"

I found some interesting links regarding this, but it looks like there is nothing in guava to do the job...

StackOverflow: "Sort on a String that may contain a number"
A good explanation of the: The Alphanum Algorithm

Community
  • 1
  • 1
Chriss
  • 5,157
  • 7
  • 41
  • 75
  • 3
    What's wrong with the `Alphanum Algorithm`? It seems to be what you want. And why do you need "Guava"? Just use `Collections.sort(list, comparator);` – Bohemian Jan 09 '12 at 20:25
  • There is nothing wrong with "Alphanum Algorithm", i don't want to reeinvent the wheel (if there is a wheel)! `Collections.sort(list, comparator)` needs the `Comperator` i'am asking for. – Chriss Jan 09 '12 at 20:29
  • 1
    Is downloading the [pre-written java](http://www.davekoelle.com/files/AlphanumComparator.java) (albeit non-generic) really "reinventing the wheel"? Perhaps, but it's certainly "low hanging fruit". – Bohemian Jan 09 '12 at 20:33
  • 1
    Possible duplicate of [this question](http://stackoverflow.com/questions/1262239/natural-sort-order-string-comparison-in-java-is-one-built-in) which links to an [open-source implementation](http://www.java2s.com/Open-Source/Java-Document/Science/Cougaar12_4/org/cougaar/util/NaturalOrderComparator.java.htm) – user949300 Jan 09 '12 at 20:35
  • 1
    I'am looking for a pure Guava solution, because i don't want to wrap every opensource lib to a osgi-bundle, just for one useful feature! Guava has many great features just in one jar. Give it a try, you won't regret it. – Chriss Jan 09 '12 at 21:05
  • @Chriss OSGi bundle? One source file?! Pity I cannot -1 you. – alf Jan 09 '12 at 21:27
  • @alf Sorry, i am not a native speaker. Of cause i dont want to wrap one class in one bundle. Also i don't want to put 100 classes of a opensource-lib in one bundle, only to use 1 class out of 100. – Chriss Jan 11 '12 at 18:47

2 Answers2

4

No, there isn't any built in implementation of such a comparator in Guava... seems like something that's too narrowly applicable to me. Just write your own implementation or use one of the existing ones that have been linked already.

ColinD
  • 108,630
  • 30
  • 201
  • 202
0

Take a look http://lucene.apache.org/java/3_5_0/api/all/org/apache/lucene/util/NumericUtils.html