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

MAG*_*Gx2 21 java sorting

我对字符串的默认比较器(在SortedSet中)有问题.问题是默认比较器没有排序包含数字的良好字符串,即:在集合中我有:

room1, room2, room100
Run Code Online (Sandbox Code Playgroud)

自然排序应该如上所述,但在集合中我有:

room1, room100, room2
Run Code Online (Sandbox Code Playgroud)

我知道它为什么但我不知道如何改变它.

Boh*_*ian 42

尝试使用此比较器,删除所有非数字字符,然后将剩余字符作为数字进行比较:

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

这是一个测试:

public static void main(String[] args) throws IOException {
    List<String> strings = Arrays.asList("room1", "foo", "room2", "room100", "room10");
    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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

[foo, room1, room2, room10, room100]
Run Code Online (Sandbox Code Playgroud)


vam*_*msi 8

使用了@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);
            }
        });
Run Code Online (Sandbox Code Playgroud)


RNJ*_*RNJ 6

试试这个.我假设你的字符串开头总是有"空间".

    List<String> list = Arrays.asList("room1", "room100", "room2");
    Collections.sort(list, new Comparator<String>()
    {
        @Override
        public int compare(String o1, String o2)
        {
            return new Integer(o1.replaceAll("room", ""))
                .compareTo(new Integer(o2.replaceAll("room", "")));
        }

    });
Run Code Online (Sandbox Code Playgroud)