Reputation: 534
So I have a list of a bunch of alphanumeric items like...
"123456"
"alpha"
"tango"
"beta"
...
I was looking to use Collections.sort()
for the sorting of this list, but I need to sort in the order (1234,AAAA,aaaa,BBBB,bbbb,...)
with numbers first, followed by upper then lower case words. All the elements are strings including any apparent numbers. Would Collections.sort()
handle this case since they are all actually strings, or if not what Comparator
would I use to accomplish this?
Or is there some other way that might be more efficient to accomplish this like using regular expressions?
Thanks.
Upvotes: 3
Views: 207
Reputation: 328598
You could use a Collator:
List<String> list = Arrays.asList("1234","AAAA","aaaa","BBBB","bbbb");
Collator c = Collator.getInstance(Locale.ENGLISH);
c.setStrength(Collator.CANONICAL_DECOMPOSITION);
Collections.sort(list);
System.out.println("without collator: " + list);
Collections.sort(list, c);
System.out.println("with collator: " + list);
outputs:
without collator: [1234, AAAA, BBBB, aaaa, bbbb]
with collator: [1234, AAAA, aaaa, BBBB, bbbb]
Note: you may need a different collator for what you need although this one seems fine. In the worst case scenario, you can create a RuleBaseCollator
with your specific rules.
Upvotes: 5