简体   繁体   中英

Convert python sorting of list to java code.

I am trying to convert this python code that sorts my items list into java code. How can i do this kind of sorting in 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']

So far what i have in java is the following:

//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)

Thanks

You'll need to use a custom Comparator in place of the lambda expression declared in your python script.

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

Please note that this Comparator doesn't compare the letter component, simply because the lambda expression doesn't either.

Collections.sort accepts comparators as well.

So, you can do this --

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM