简体   繁体   中英

How to sort an array of strings by everything but the first letter

My array is expected to have elements that look like "B1" and "C22" for any letter AZ and number 1-26 . I need to sort this array numerically, so we don't consider the first character of the string when sorting. So that an array {"B1", "A22", "C9"} would be sorted to {"B1", "C9", "A22"} .

I have tried to take a substring, but it doesn't work since I don't know which strings will be of length 3 and which will be of length 2.

You can create your own comparator that ignores some of the characters :

Arrays.sort(s, new MyComparator());
System.out.println(Arrays.toString(s));

class MyComparator implements Comparator<String> {


    @Override
    public int compare(String o1, String o2) {

        // Remove the chars you are want to ignore from o1, o2 
        o1 = o1.substring(1);
        o2 = o2.substring(1);
        return Integer.compare(Integer.parseInt(o1),Integer.parseInt(o2));
        // return o1.compareTo(o2); see petr note bellow
    }
}

If the array contains a huge number of elements, then you can replace Arrays.sort() with Arrays.parallelSort() to sort efficiently.

Arrays.sort(arr, 
    (ele1, ele2) -> ele1.substring(1).compareTo(ele2.substring(1)));

if you are confident that substring(1) only contains numeric value, then you can sort as below:

Arrays.sort(arr, (Comparator.comparingInt(element -> 
                            Integer.parseInt(element.substring(1)))));

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