Sorting alphanumeric string in Kotlin (numeric, not lexicographical order)

68 Views Asked by At

I was trying to sort this list

val list = mutableListOf("1", "2", "10", "A10", "A1", "A2","B24C","A")
list.sort()
println(list)

It gives [1, 10, 2, A, A1, A10, A2, B24C], but what I want is [1, 2, 10, A, A1, A2, A10, B24C]

This order I want is 0-9 ascending, then A-Z ascending, like 1,2,3,A1,A2,B1,B2,etc

1

There are 1 best solutions below

0
Benjamin Ting On

What I found was if I use sort() on String, it will do a lexicographic sort. If I want a numeric kind of sort, I can do:

list.sortBy { it.toInt(Character.MAX_RADIX) }

source: https://www.reddit.com/r/Kotlin/comments/118bvui/comment/j9ib8q4