reedaccess_
reedaccess_

Reputation: 80

How to sort an array of Strings based on the parsed first digit

I just finished a coding competition where one of the problems required me to sort an array of strings, but numerically based on the number that appeared first in the string. for example:

String[] array = 
{{"18.sdfahsdfkjadf"},
 {"1.skjfhadksfhad"},
 {"2.asldfalsdf"}};

would need to be sorted as 1.sk... first, 2.as..., and then 18.sd... last. But if you use (in Java) Arrays.sort(array), it would be ordered as 1, 18, then 2 because its going off the the first char first and not as a number.

Upvotes: 1

Views: 763

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79580

You can split each string on \D (which means non-digit) and compare the strings based on the first elements, parsed into an integer, of the resulting arrays.

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        String[] array = { "18.sdfahsdfkjadf", "1.skjfhadksfhad", "2.asldfalsdf" };
        
        Arrays.sort(array, 
                        (s1, s2) -> 
                            Integer.compare(
                                                Integer.parseInt(s1.split("\\D")[0]),
                                                Integer.parseInt(s2.split("\\D")[0])
                                            )
                    );

        System.out.println(Arrays.toString(array));
    }
}

Output:

[1.skjfhadksfhad, 2.asldfalsdf, 18.sdfahsdfkjadf]

Upvotes: 3

user4910279
user4910279

Reputation:

Try this.

Arrays.sort(array, Comparator.comparingInt(s -> Integer.parseInt(s.split("\\.")[0])));
System.out.println(Arrays.toString(array));

output:

[1.skjfhadksfhad, 2.asldfalsdf, 18.sdfahsdfkjadf]

Upvotes: 2

christianfoleide
christianfoleide

Reputation: 56

Using the Streams API, you could produce something like this (assuming the numbers are always separated from the rest by punctuation):

List<String> sorted = Arrays.stream(array).sorted((s1, s2) -> {
         Integer i = Integer.parseInt(s1.split("\\.")[0]);
         Integer j = Integer.parseInt(s2.split("\\.")[0]);
         return i.compareTo(j);
}).collect(Collectors.toList());

With the resulting array being: [1.skjfhadksfhad, 2.asldfalsdf, 18.sdfahsdfkjadf]

Upvotes: 2

Related Questions