Forums Register Login

number sorting having prefix letter

+Pie Number of slices to send: Send
hi team,

i had a list of some numbers having a prefix A like A12 , A55, A76 ,A111 ,A888, A88 ,A880 A111 , A11,A1

i need to sort this list so the result would be A1,A11,A12,A55,A76....

please suggest me how to do this. can i use arrays.sort method to achieve the same or any other way.
+Pie Number of slices to send: Send
 

prithvi pandey wrote:can i use arrays.sort method to achieve the same or any other way.



Yes. The Arrays.sort() method will work, but you will need to provide a custom comparator. The default string comparator uses ASCII ordering, so "A2" comes after "A11", which is probably not what you want.

Henry
+Pie Number of slices to send: Send
Welcome to the Ranch
Those are not numbers, but Strings. You can sort them as Strings but beware: A10 will come before A9.
+Pie Number of slices to send: Send
 

Campbell Ritchie wrote:Welcome to the Ranch
Those are not numbers, but Strings. You can sort them as Strings but beware: A10 will come before A9.


Hence the need for a custom comparator!

Prithvi: With a custom comparator, you get the two Strings as input and can have any logic you want.
Roses are red, violets are blue. Some poems rhyme and some don't. And some poems are a tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 500 times.
Similar Threads
protected method not being overridden in diff. package
threads
I am also in elite group of SCJP-2.0
inheritance
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 17:32:28.