Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sorting an String Array by a Substring of characters

I need to sort an array of strings like the following, by a substring of characters:

[0] = "gtrd3455";
[1] = "wsft885";
[2] = "ltzy96545";
[3] = "scry5558";
[4] = "lopa475";

I need to sort by the following "3455, 885, 96545, 5558, 475" I need to substring off the first 4 characters of the array, sort it and display back in an array like the output below.

The output should be an array like:

[0] = "ltzy96545";
[1] = "scry5558";
[2] = "gtrd3455";
[3] = "wsft885";
[4] = "lopa475";

Example of how I can do this in Java?

like image 359
Jsn0605 Avatar asked Dec 06 '25 19:12

Jsn0605


1 Answers

You can use a Comparator, and use Array#sort method with it, to sort it according to your need: -

String[] yourArray = new String[3];
yourArray[0] = "gtrd3455";
yourArray[1] = "ltzy96545";
yourArray[2] = "lopa475";

Arrays.sort(yourArray, new Comparator<String>() {
    public int compare(String str1, String str2) {
        String substr1 = str1.substring(4);
        String substr2 = str2.substring(4);

        return Integer.valueOf(substr2).compareTo(Integer.valueOf(substr1));
    }
});

System.out.println(Arrays.toString(yourArray));

OUTPUT: -

[ltzy96545, gtrd3455, lopa475]
like image 127
Rohit Jain Avatar answered Dec 08 '25 08:12

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!