1

I have a sequences of numbers in String and I want to sort them. For example:

From: 3,4,16;1,5,16,18,19;12,14,15,17;6,10,11;

To: 1,5,16,18,19;3,4,16;6,10,11;12,14,15,17;

My code:

String test = "3,4,16;1,5,16,18,19;12,14,15,17;6,10,11;";
String sortedTest[] = test.split(";");
Arrays.sort(sortedTest);
for(String i: sortedTest)
    System.out.print(i +";");

But obviously when I use Array.sort() on this I get:

12,14,15,17;1,5,16,18,19;3,4,16;6,10,11;

How can I get it sorted like in example?

Halep
  • 93
  • 1
  • 1
  • 12
  • You should definitely mention the way they get sorted! This took me around 3 minutes to visually get rid of the commata and semicolons to understand the sorting... – geisterfurz007 Nov 29 '16 at 09:30

3 Answers3

2

You can use sort with custom comparator:

Arrays.sort(sortedTest, (arr1, arr2) -> Integer.valueOf(arr1.split(",")[0]).compareTo(Integer.valueOf(arr2.split(",")[0])));
Viet
  • 3,349
  • 1
  • 16
  • 35
1

You need to implement a comparator that will transform the String value as an Integer, so this will be properly sorted.

Here is an example: Java Comparator class to sort arrays

Then, with a specific Comparator, you can describe entirely the way your data is set in your Array and the way you wanna sort them

Community
  • 1
  • 1
DamCx
  • 1,047
  • 1
  • 11
  • 25
0

I think you can use this:
if you are using java 7:

String test = "3,4,16;1,5,16,18,19;12,14,15,17;6,10,11;";
String sortedTest[] = test.split(";");
Arrays.sort(sortedTest, new Comparator<String[]>() {
    @Override
    public int compare(String[] o1, String[] o2) {
        //TODO you can change the compare rule
        return o1[0].compareTo(o2[0]);
    }
});


if you are using java 8:

String test = "3,4,16;1,5,16,18,19;12,14,15,17;6,10,11;";
String sortedTest[] = test.split(";");
Arrays.sort(sortedTest, Comparator.comparing((String[] arr) -> arr[0])
                                      .reversed());
JonahCui
  • 125
  • 1
  • 5
  • Already written in the following question : http://stackoverflow.com/questions/5393254/java-comparator-class-to-sort-arrays Thanks to not duplicate answers – DamCx Nov 29 '16 at 09:48