java - 将 python 列表排序转换为 java 代码。

标签 java python

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

python代码:

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)

谢谢

最佳答案

您需要使用自定义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 表达式也不比较。

关于java - 将 python 列表排序转换为 java 代码。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12531739/

相关文章:

java - 如何在 Java 的抽象类中强制实现嵌套抽象类?

Java - 程序运行后关闭计算机

python - 使用 Python 生成扁平化的 PDF

python - 开发Django项目时Docker是否可以替代 'virtualenv'?

python - 带有服务帐户的 Google Cloud Pub Sub

python - 如何在 python 中使用 raw_input 将元组作为输入?

java.lang.NoSuchFieldError : name at run time in hibernate project 错误

java - 正则表达式动态忽略给定路径的某些部分

java - activator 1.3.0 导致 sbt 项目出错?

python - 获取警告的回溯