对 Java 中包含数字的字符串进行排序

2022-09-01 09:19:39

我对字符串的默认比较器(在排序集中)有问题。问题是默认比较器不能对包含数字的良好字符串进行排序,即:在set i中有:

room1, room2, room100

自然排序应该像上面一样,但在集合中我有:

room1, room100, room2

我知道为什么会这样,但我不知道如何改变它。


答案 1

试试这个比较器,它会删除所有非数字字符,然后将其余字符比较为数字:

Collections.sort(strings, new Comparator<String>() {
    public int compare(String o1, String o2) {
        return extractInt(o1) - extractInt(o2);
    }

    int extractInt(String s) {
        String num = s.replaceAll("\\D", "");
        // return 0 if no digits found
        return num.isEmpty() ? 0 : Integer.parseInt(num);
    }
});

这是一个测试:

public static void main(String[] args) throws IOException {
    List<String> strings = Arrays.asList("room1.2", "foo1.1", "foo", "room2.3", "room100.999", "room10", "room.3");

    Collections.sort(strings, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return extractInt(o1) - extractInt(o2);
        }

        int extractInt(String s) {
            String num = s.replaceAll("\\D", "");
            // return 0 if no digits found
            return num.isEmpty() ? 0 : Integer.parseInt(num);
        }
    });
    System.out.println(strings);
}

输出:

[foo, room1, room2, room10, room100]

当数字是小数时(也演示了Java 8 +样式):

public static void main(String[] args) {
    List<String> strings = Arrays.asList("room1.2", "foo1.1", "room2.3", "room100.999", "room10", "room.3");
    Collections.sort(strings, Comparator.comparing(Application::extractDouble));
    System.out.println(strings);
}

static double extractDouble(String s) {
    String num = s.replaceAll("[^\\d.]", "");
    // return 0 if no digits found
    return num.isEmpty() ? 0 : Double.parseDouble(num);
}

结果:

[foo, room.3, foo1.1, room1.2, room2.3, room10, room100.999]

答案 2

用@bohemian答案。只是改进了一点。这对我来说很好。

        Collections.sort(asdf, new Comparator<String>() {
            public int compare(String o1, String o2) {

                String o1StringPart = o1.replaceAll("\\d", "");
                String o2StringPart = o2.replaceAll("\\d", "");


                if(o1StringPart.equalsIgnoreCase(o2StringPart))
                {
                    return extractInt(o1) - extractInt(o2);
                }
                return o1.compareTo(o2);
            }

            int extractInt(String s) {
                String num = s.replaceAll("\\D", "");
                // return 0 if no digits found
                return num.isEmpty() ? 0 : Integer.parseInt(num);
            }
        });

推荐