簡體   English   中英

將列表的python排序轉換為java代碼。

[英]Convert python sorting of list to java code.

我正在嘗試將此python代碼轉換為將我的items列表排序為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)

謝謝

您需要使用自定義的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表達式也不會。

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
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM