Anthony Taylor
Anthony Taylor

Reputation: 3393

Sorting Objects Alphanumerically

I am running into an issue when trying to sort a List of "Routes" for my app, no matter what I try, I cannot obtain the sorting that I am looking for.

I want it sorted 1,2,3,4,5, etc but when I sort, I get 1,11,12,2,20 and so on.

My Route model is

public open class Route(docValue:Map<String,Any>) {
    val route_id = (docValue["route_id"] as Number).toInt()
    val short_name = docValue["route_short_name"] as String
    val color = readColorMoreSafely(docValue, "route_color", Color.BLUE)
    val long_name = docValue["route_long_name"] as String 
}

The code used to sort is

if(cityId != null && view != null) {
        val routesList = view.findViewById(R.id.routesList) as ListView
        val cache = TransitCache.getInstance(applicationContext, cityId, true)
        val routes = cache.getRoutes()
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext {
                val noRoutesMessage = view.findViewById(R.id.list_routes_no_routes_visible) as TextView
                noRoutesMessage.visibility = if(it.size == 0) View.VISIBLE else View.GONE
            }
        routes.toSortedList()
        listAdapter = RxListAdapter(applicationContext, R.layout.activity_list_routes_row, routes)
        routesList.adapter = listAdapter

But still nothing, I just want to sort the routes by "route_id", i've tried a few different things, the last one of which was

routes.toSortedList()

which still ended up not doing what I wanted, at this point I'm stuck.

Upvotes: 3

Views: 569

Answers (2)

Kiskae
Kiskae

Reputation: 25573

val routes = cache.getRoutes()
        .observeOn(AndroidSchedulers.mainThread())

This code tells me you're dealing with RxJava, which requires an entirely different solution so in the future it is important to include that type of information.

If cache.getRoutes() returns an Observable<List<Route>> then that route can be sorted with the code

.map { 
    it.sortedBy(Route::route_id)
}

This will produce a new inner list sorted by the numerical value of route_id.

If cache.getRoutes() returns Observable<Route> then you need to include the additional call to .toList() to turn it into an Observable<List<Route>>.

Upvotes: 4

mfulton26
mfulton26

Reputation: 31234

If routes is a MutableList and you want to sort it in-place then you can use sortBy:

routes.sortBy(Route::route_id)

Otherwise you can use sortedBy to create a new list with the elements sorted:

val sortedRoutes = routes.sortedBy(Route::route_id)

Upvotes: 2

Related Questions