java - How to sort Alphanumeric String -
i have problem sorting strings include integers. if use below code sorting like: 1some, 2some, 20some, 21some, 3some, some
however want sorted like: 1some, 2some, 3some, 20some, 21some, some
how can this?
thanks!
collections.sort(selectednodes, new comparator<defaultmutabletreenode>() { @override public int compare(defaultmutabletreenode o1, defaultmutabletreenode o2) { return o1.getuserobject().tostring() .compareto(o2.getuserobject().tostring()); } });
here self-contained example on how (not particularly optimized):
final pattern p = pattern.compile("^\\d+"); string[] examples = { "1some", "2some", "20some", "21some", "3some", "some", "1abc", "abc" }; comparator<string> c = new comparator<string>() { @override public int compare(string object1, string object2) { matcher m = p.matcher(object1); integer number1 = null; if (!m.find()) { return object1.compareto(object2); } else { integer number2 = null; number1 = integer.parseint(m.group()); m = p.matcher(object2); if (!m.find()) { return object1.compareto(object2); } else { number2 = integer.parseint(m.group()); int comparison = number1.compareto(number2); if (comparison != 0) { return comparison; } else { return object1.compareto(object2); } } } } }; list<string> exampleslist = new arraylist<string>(arrays.aslist(examples)); collections.sort(exampleslist, c); system.out.println(exampleslist);
output
[1abc, 1some, 2some, 3some, 20some, 21some, abc, some]
explanation
- the example uses constant
pattern
infer whether number instring
's starting position. - if not present in first
string
, compares second. - if present indeed in first, checks second.
- if not present in second, compares 2
string
s is, again - if present in both, compares
integer
s instead of wholestring
s, hence resulting in numerical comparison rather lexicographical one - if number compare identical, goes lexicographic comparison of whole
string
s (thanks mihaic spotting one)
Comments
Post a Comment