比较不强制转换的部分数字字符串

Compare partially-numeric string without casting

我用谷歌搜索了一下,但没能找到解决这个特定问题的方法。我有一个 List 的 POJO,它确实有一个名为 displayCode 的字段(字符串类型)。 displayCode 可以有不同的格式。一些例子:

622
622-S
622-1
623 
624
625
625-S
625-1
625-1-S
625-2
625-2-S

排序后它们也应该按照上面显示的顺序。使用正常的 s1.compareTo(s2); 我得到这样的订单:

1
10
100
101
102
...

这显然不符合我的需要。遗憾的是,我没有计划如何以任何顺利的方式(也没有其他方式)实现这一目标。另请注意,我不能使用 Java 8.

中的任何内容

用于测试目的的代码(您可以尝试一下):

List<String> s = new ArrayList<String>(Arrays.asList(new String[] { "622", "622-S", "622-1", "623", "625",
        "625-S", "625-1", "625-1-S", "625-2", "625-2-S", "6", "60", "666", "1", "2", "3" }));
Collections.sort(s,new Comparator<String>() {

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

        return 0;
    }
});
System.out.println(s);

编辑: 我的第一个想法是将第一个 - 之前的数字转换为一个 int 并将其进行比较,然后按照我的方式处理其他部分。然而,这听起来并不顺利。

除了分离每个字符串的数字部分,转换为数字,比较它们,只有当它们相等时才对字符串进行字典顺序比较。

例如,沿着这些线(概念,可能需要调整):

@Override
public int compare(String o1, String o2) {
    String[] p1 = o1.split(" ", 2);
    String[] p2 = o2.split(" ", 2);
    try {
        int n1 = Integer.parseInt(p1[0]);
        int n2 = Integer.parseInt(p2[0]);
        if (n1 != n2) {
            return n1 - n2;
        }
        boolean s1 = p1.length > 1 && p1.equals("S");
        boolean s2 = p2.length > 1 && p2.equals("S");
        if (s1 && !s2) {
            return -1;
        }
        if (!s1 && s2) {
            return 1;
        }
    } catch (NumberFormatException e) {
    }
    return o1.compareTo(o2);
}

Java 字符串有一个 split 方法,您可以使用它来隔离 POJO 的数字部分;然后您可以使用 parseInt 将 POJO 获取为整数,这将使排序方式变得容易。

这可能对您有所帮助。

Collections.sort(s, new Comparator<String>() {

            public int compare(String o1, String o2) {
                int returnValue = -1;

                Integer left = returnIfNumeric(o1);
                Integer right = returnIfNumeric(o2);

                // if both values are number
                if (left != null && right != null) {
                    if (left > right)
                        returnValue = 1;
                    else if (left == right)
                        returnValue = 0;
                    else
                        returnValue = -1;
                } 
                // if both values are string
                else if (left == null && left == right) {
                    return o1.compareTo(o2);
                }
                // if left is number
                else if (left != null) {
                    returnValue = -1;
                }
                // if left is string
                else {
                    returnValue = 1;
                }

                return returnValue;
            }
        });

    }

    public static Integer returnIfNumeric(String str) {
        Integer number = null;
        try {
            number  = Integer.valueOf(str);
        } catch (NumberFormatException nfe) {
            number = null;
        }
        return number;
    }