Halep
Halep

Reputation: 93

Sorting sequences of numbers in String by first value in Java

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?

Upvotes: 1

Views: 305

Answers (3)

JonahCui
JonahCui

Reputation: 145

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());

Upvotes: 0

Viet
Viet

Reputation: 3409

You can use sort with custom comparator:

Arrays.sort(sortedTest, (arr1, arr2) -> Integer.valueOf(arr1.split(",")[0]).compareTo(Integer.valueOf(arr2.split(",")[0])));

Upvotes: 2

DamCx
DamCx

Reputation: 1047

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

Upvotes: 1

Related Questions