Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting collections with string elements in java

I have a collections...i wrote code to sort values using my own comparator my comparator code is

private static class MatchComparator implements Comparator<xmlparse> {
    @Override
    public int compare(xmlparse object1, xmlparse object2) {
        String match1 = object1.getMatchId();
        String match2 = object2.getMatchId();
        return match1.compareTo(match2);
    }
}

I will call Collections.sort(list,new MatchComparator());

Everything is fine but my problem is the sorted list is wrong when i print it...

Input for list

Match19
Match7
Match12
Match46
Match32

output from the sorted list

Match12
Match19
Match32
Match46
Match7

my expected output is

Match7
Match12
Match19
Match32
Match46
like image 684
Kandha Avatar asked Jul 16 '26 01:07

Kandha


2 Answers

to get the order you need, you could either prefix the 1 digit numbers with zero ( eg Match07 ) or you have to split the string in a prefix and a numeric part, and implement the sorting as numeric comparison

like image 124
Nikolaus Gradwohl Avatar answered Jul 17 '26 16:07

Nikolaus Gradwohl


The problem is that String.compareTo(..) compares the words char by char.

If all string start with Match, then you can easily fix this with:

public int compare(xmlparse object1, xmlparse object2) {
    String match1 = object1.getMatchId();
    String match2 = object2.getMatchId();
    return Integer.parseInt(match1.replace("Match"))
         - Integer.parseInt(match2.replace("Match"));
}

In case they don't start all with Match, then you can use regex:

Integer.parseInt(object1.replaceAll("[a-zA-Z]+", ""));

Or

Integer.parseInt(object1.replaceAll("[\p{Alpha}\p{Punch}]+", ""));

And a final note - name your classes with uppercase, camelCase - i.e. XmlParse instead of xmlparse - that's what the convention dictates.

like image 33
Bozho Avatar answered Jul 17 '26 14:07

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!