Saturday, 15 February 2014

java - How to correctly order an ArrayList containing Strings and numbers? -



java - How to correctly order an ArrayList<String> containing Strings and numbers? -

i trying order arraylist of string elements (called myarraylist) according numbers found after word "item". here snippet of in myarraylist:

item 1 item 2 item 3 ... item 9 item 10

i order myarraylist next order:

item 10 item 9 item 8 ... item 3 item 2 item 1

so far, have tried:

collections.sort(myarraylist, string.case_insensitive_order); collections.reverse(myarraylist);

however, orders myarraylist in next order

item 9 item 8 ... item 3 item 2 item 10 item 1

as can see, item 10 out of place, because reads "10" first number, "1". know how appropriately order myarraylist in reverse numerical order?

that's because default string comparator uses lexicographical order -- i.e. character character, in dictionary. since "1" comes before "2", string starting "1" precede other starting "2".

you should utilize custom comparator implement natural sorting. illustration alphanum, dave koelle, utilize this:

collections.sort(myarraylist, new alphanumcomparator());

java android sorting arraylist

No comments:

Post a Comment