1

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.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
teddyzhng
  • 80
  • 7

3 Answers3

3

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]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • so when I split with the \\D regex pattern it creates an array that, for example, {18, sdfahsdfkjadf} ? – teddyzhng Apr 11 '21 at 22:05
2

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]

2

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]