1

我正在尝试将这个对我的items列表进行排序的 python 代码转换为 java 代码。我怎样才能在java中进行这种排序?

python code:

import re
items = ['10H', '10S', '2H', '3S', '4S', '6C', '7D', '8C', '8D', '8H', '11D', '11H', '12H']
sortedItems = sorted(items, key=lambda x:int(re.findall(r'(\d+)[A-Z]*$',x)[0]))

#print sortedItems will result to the following sorted data which is what i wanted
#['2H', '3S', '4S', '6C', '7D', '8C', '8D', '8H', '10H', '10S', '11D', '11H', '12H']

到目前为止,我所拥有的java是以下内容:

//code something like this
ArrayList<String> items = new ArrayList<String>(Arrays.asList("10H", "10S", "2H", "3S", "4S", "6C", "`7D", "8C", "8D", "8H", "11D", "11H", "12H"));
Collections.sort(items)

谢谢

4

2 回答 2

4

您需要使用自定义Comparator来代替 Python 脚本中声明的 lambda 表达式。

Collections.sort(items,  new Comparator<String>() {
    private Pattern p = Pattern.compile("(\d+)[A-Z]*)");
    public int compare(String o1, String o2) {
        Matcher m1 = p.matcher(o1);
        Matcher m2 = p.matcher(o2);

        return Integer.valueOf(m1.group(0)).compareTo(Integer.valueOf(m2.group(0)));
    }
});

请注意,这Comparator不会比较字母组件,因为 lambda 表达式也不会。

于 2012-09-21T13:43:29.930 回答
2

Collections.sort 也接受比较器。

所以,你可以这样做——

Collections.sort(items, new Comparator<String>() {
    @Override
    public int compareTo(String s1, String s2) {
           // do your magic here , by extracting the integer portion, comparing those
           // and then comparing the string to return 1 , 0 , -1
    }
});
于 2012-09-21T13:45:26.293 回答