gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:33:02 25 4
gpt4 key购买 nike

我正在尝试将这个对我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com