1

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm thinking of Collections.sort(T[] items,..) but i can't get it to work. I'm really new to java. :)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.