字符串列表排序(数字大小排序,中间由_或-分割的字符串)

发布于 2021-03-17  1453 次阅读


public class test {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1_2_3");
        list.add("1_2_4");
        list.add("1_2_4-1");
        list.add("1_2_13");
        list.add("1_2_2");
        list.add("1_2_2_1");
        list.add("1_2_2_3");
        list.add("1_2_2_3_3131");
        list.add("1_2_2_2");
        compare(list);
        System.out.println(list);
    }

    /**
    * 字符串列表排序
    * ["1_2_3","1_2_4","1_2_2_1","1_2_2_3_3131"] 排序
    */
    private static void compare(List<String> list) {
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                 if (ObjectUtils.isEmpty(o1) || ObjectUtils.isEmpty(o2)) {
                    return -1;
                }
                String[] temp1 = o1.toString().split("[- _]");
                String[] temp2 = o2.toString().split("[- _]");
                String[] str1;
                String[] str2;
                if (temp1.length > temp2.length) {
                    str1 = temp1;
                    str2 = temp2;
                } else {
                    str1 = temp1;
                    str2 = temp2;
                }
                for (int i = 0; i < str1.length; i++) {
                    if (i <= (str2.length - 1)) {
                        if (Long.valueOf(str1[i]) > Long.valueOf(str2[i])) {
                            return 1;
                        } else if (Long.valueOf(str1[i]) < Long.valueOf(str2[i])) {
                            return -1;
                        } else {
                            continue;
                        }
                    } else {
                        return 1;
                    }
                }
                return 0;
            }
        });
    }

届ける言葉を今は育ててる
最后更新于 2021-03-17