How to sort Alphanumeric String

前端 未结 11 1422
我寻月下人不归
我寻月下人不归 2020-12-10 06:25

I have a problem with sorting strings which include integers. If I use the below code I get sorting like: 1some, 2some, 20some, 21some, 3some, some

However I want it

11条回答
  •  -上瘾入骨i
    2020-12-10 07:11

    You can do the core of it in one line using regex to extract the numeric part:

    Collections.sort(selectedNodes, new Comparator() {
        @Override
        public int compare(DefaultMutableTreeNode o1,
            DefaultMutableTreeNode o2) {
            return Integer.parseInt(o1.getUserObject().toString().replaceAll("\\D", "")) -
                Integer.parseInt(o2.getUserObject().toString().replaceAll("\\D", ""));
        }
    });
    

提交回复
热议问题