1

I have an ArrayList<String> containing a list of 'Building Key' numbers.
Forgive me if this has been answered before I am struggling to find a solution by searching.

public class SortKeyNumbers {
    
    public static void main(String args[]) {
        
        ArrayList<String> keys = new ArrayList<>();
        
        keys.add("1");
        keys.add("10");
        keys.add("2");
        keys.add("3");
        keys.add("3B");
        keys.add("12");
        keys.add("12C");
        keys.add("21");
        keys.add("32");
        
        Collections.sort(keys);
        
        System.out.println(keys);
        
    }
    
}

This gives me an output of [1, 10, 12, 12C, 2, 21, 3, 32,3B]
I know that this is as expected from Collections.sort
What I need is an output of [1, 2, 3, 3B, 10, 12, 12C, 21, 32]

What I am asking is help to write the correct comparator or compareTo to achieve the desired output.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
tonkatommy
  • 13
  • 2
  • *What I am asking is help to write the correct comparator or compareTo to achieve the desired output.* - where is your attempt? Maybe we can make a suggestion on how to improve it. We don't even know the full requirements. For example, can it only contain a single character at the end or multiple characters. What comes first "12" or "12C"? – camickr Aug 24 '20 at 03:04

2 Answers2

0

You can use a comparator function which strips any non-digit characters out of the key and then parses it to an integer:

Collections.sort(keys, Comparator.comparing(s -> Integer.parseInt(s.replaceAll("[^\\d]", ""))));

Output:

[1, 2, 3, 3B, 10, 12, 12C, 21, 32]
Nick
  • 138,499
  • 22
  • 57
  • 95
  • Seems so easy! I tried adding "12B" after adding "12C" but it doesn't sort them alphanumerically. Is there a way to incorporate that as well? – tonkatommy Aug 24 '20 at 02:55
  • @tonkatommy. *Is there a way to incorporate that as well?* - write a proper Comparator and incorporate all your rules into the Comparator. – camickr Aug 24 '20 at 03:10
  • @tonkatommy if you first sort alphabetically (`Collections.sort(keys)`) and then use this function, those values will sort as you desire (because Java sort is stable) – Nick Aug 24 '20 at 03:11
0

You can use ArrayList.sort and just compare only integers by removing non digits

keys.sort(Comparator.comparing(str-> Integer.valueOf(str.replaceAll("\\D+",""))));
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98