按字母排序对象
当我尝试为我的应用排序“路由”列表时遇到了一个问题,不管我尝试什么,我无法获得我正在寻找的排序。
我想要它排序1,2,3,4,5等,但当我排序,我得到1,11,12,2,20等。
我的路线模型是
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 }
用来排序的代码是
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
但仍然没有,我只是想通过“route_id”来排序路线,我尝试了一些不同的东西,最后一个是
routes.toSortedList()
这仍然没有做我想要的,在这一点上,我卡住了。
val routes = cache.getRoutes() .observeOn(AndroidSchedulers.mainThread())
这段代码告诉我你正在处理RxJava,它需要一个完全不同的解决方案,因此将来必须包含这种类型的信息。
如果cache.getRoutes()
返回一个Observable<List<Route>>
那么该路由可以用代码排序
.map { it.sortedBy(Route::route_id) }
这将产生一个新的内部列表,按照route_id
的数值排序。
如果cache.getRoutes()
返回Observable<Route>
那么你需要包含额外的调用.toList()
把它变成一个Observable<List<Route>>
。
如果routes
是一个MutableList
并且你想对它进行排序,那么你可以使用sortBy
:
routes.sortBy(Route::route_id)
否则,你可以使用sortedBy
来创建一个新的列表,其元素排序为:
val sortedRoutes = routes.sortedBy(Route::route_id)
这可以使用lambda表达式来完成。
route.Sort((x, y) => Int32.Parse(x.Number).CompareTo(Int32.Parse(y.Number)));