0

I want to sort a few strings:

 RANDOM.XY
 AAA.BBB.CC
 AAA.BBB
 RANDOM.XY.Z
 AAA.BBB.CC.D

The sorted order should be:

 AAA.BBB
 AAA.BBB.CC
 AAA.BBB.CC.D
 RANDOM.XY
 RANDOM.XY.Z

I put them in an ArrayList list, and used a built-in sort method:

 Collections.sort(list);

However, what I get from the sorting is:

 AAA.BBB.CC.D
 AAA.BBB.CC
 AAA.BBB
 RANDOM.XY.Z
 RANDOM.XY

How should I go about this?

HoneyWine
  • 177
  • 1
  • 4
  • 18
  • 1
    You should implement a custom Comparator. See https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29 – torvin Sep 24 '15 at 00:46
  • [Sorting an array of String with custom ordering](http://stackoverflow.com/questions/16541314/sorting-an-array-of-string-with-custom-ordering) and then create something that looks a lot like [String.compareTo](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.compareTo%28java.lang.String%29) (or possibly something a lot simpler which just *calls* that method. – Bernhard Barker Sep 24 '15 at 00:52
  • 2
    I cannot reproduce the behavior you are describing ([demo](http://ideone.com/AgB6IU)). – Sergey Kalinichenko Sep 24 '15 at 00:55
  • 1
    @dasblinkenlight I suspect he mixed up what he wants and what he gets. – Bernhard Barker Sep 24 '15 at 00:56

1 Answers1

2

You can create your custom class that contains the original string and a string that doesn't contain the dots. You then can implement the Comparator interface and compare the strings that doesn't contain the dots.

Peter Zhu
  • 421
  • 6
  • 16