I need to group and sort an API result by 1st character of name. All names starting with a letter should come in order, followed by names starting with non-alphabet grouped into "#" and placed at end. Below is a simplified code:
data class Model(val title: String)
fun main() {
val mList = arrayListOf(Model("pqr"), Model("abc"), Model("3AM"), Model("%s5"))
val mComparator = Comparator<String> { o1, o2 ->
when {
o1 == "#" -> 1
o2 == "#" -> -1
else -> o1.compareTo(o2)
}
}
val mMap = mList.groupBy {
if (it.title[0].isLetter()) it.title[0].toString()
else "#"
}.toSortedMap(mComparator)
val outList = arrayListOf<List<Model>?>()
mMap.keys.forEach {
outList.add(mMap[it])
}
println(mMap)
println(mMap.keys)
println(mMap.values)
println(mMap["#"])
println(outList)
}
Here's output of above code:
{a=[Model(title=abc)], p=[Model(title=pqr)], #=[Model(title=3AM), Model(title=%s5)]}
[a, p, #]
[[Model(title=abc)], [Model(title=pqr)], [Model(title=3AM), Model(title=%s5)]]
null
[[Model(title=abc)], [Model(title=pqr)], null]
The problem is that mMap["#"] gives null although mMap, mMap.keys, mMap.values show "#" in keys and also the corresponding values.
Don't understand why mMap["#"] returns null rather than [Model(title=3AM), Model(title=%s5)]