Search code examples
javaalphanumericcolumnsorting

sort Alphanumeric values regardless of letters


input --> "123","01","123A","728R" ,"1234" Output should be 01,123,123A,728R,1234

i tried the below but not giving expected OP.

public int compare(SO o1, SO o2) {
                    if(o1.getnumber() != null && o2.getnumber()!=null) {
                        if (NumberUtils.isNumber(o1.getnumber()) &&
                                NumberUtils.isNumber(o2.v())) {
                            Long val1 = Long.valueOf(o1.getnumber());
                            Long val2 = Long.valueOf(o2.getnumber());
                            if ("asc".equals(searchSO.getSortOrder())) {
                                return (val1.compareTo(val2));
                            } else if ("desc".equals(searchSO.getSortOrder())) {
                                return (val2.compareTo(val1));
                            }
                        }
                        else{
                            if ("asc".equals(searchSO.getSortOrder())) {
                                return (o1.getnumber().compareTo(o2.getnumber()));
                            } else if ("desc".equals(searchSO.getSortOrder())) {
                                return (o2.getnumber().compareTo(o1.getnumber()));
                            }
                        }
                    }
                    return 0;
                }

Solution

  • A solution could be remove all non-numeric values from the String and then compare it. In order to replace the non-numeric values from string you can use below regex:

    str.replaceAll("[^\\d.]", "")