简体   繁体   中英

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?

您可以使用自定义比较器排序:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM