对通用对象列表进行排序 [英] Sorting a list of generic objects

查看:33
本文介绍了对通用对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个对 Seq[T] 对象执行排序的通用代码.我知道在我们知道基类及其属性之前,不可能执行排序操作.在查看此 answer 后,我接受了此代码,我的要求是处理为尽可能多的自定义数据类型.

I have a requirement to write a generic code that perform sorting on the Seq[T] objects. I know it won't be possible to perform sorting operation until we know the base class and its attributes. After taking a look into this answer I took this code and my requirement is to handle as many custom data type as possible.

case class Country(name: String, id : Int)
type CountrySorter = (Country, Country) => Boolean
def byName : CountrySorter = (c1:Country, c2:Country) => c1.name < c2.name
def byId : CountrySorter = (c1:Country, c2:Country) => (c1.id < c2.id)

val sortingMap = Map[String, CountrySorter](
  "sortByCountryName" -> byName ,
  "soryByCountryId" -> byId
 )

<小时>

函数调用


Function call

def sort[T]( input : Seq[T], criteria : String) : Seq[T] = {
  input.sortWith(sortingMap(criteria))
}

input.sortWith(sortingMap(criteria)) 在这里我得到错误,因为 sortWith 函数只需要 Country类型而不是 T 类型.

input.sortWith(sortingMap(criteria)) here I get error as sortWith function only takes Country type and not T type.

推荐答案

如果您想使用 sortWith 定义排序,这里有一个方法:

Here's an approach if you want to define your ordering using sortWith :

case class Country(name: String, id : Int)

type Sorter[T] = (T, T) => Boolean
type CountrySorter = Sorter[Country]

def byName : CountrySorter = (c1, c2) => c1.name < c2.name
def byId : CountrySorter = (c1, c2) => c1.id < c2.id

def sort[T](input: Seq[T], sorter: Sorter[T]): Seq[T] = {
  input.sortWith(sorter)
}

val countries = List(Country("Australia", 61), Country("USA", 1), Country("France", 33))

sort(countries, byName)
// res1: Seq[Country] = List(Country(Australia,61), Country(France,33), Country(USA,1))

sort(countries, byId)
// res2: Seq[Country] = List(Country(USA,1), Country(France,33), Country(Australia,61))

这篇关于对通用对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆