对通用对象列表进行排序

编程入门 行业动态 更新时间:2024-10-28 07:26:32
本文介绍了对通用对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要编写一个对 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))

更多推荐

对通用对象列表进行排序

本文发布于:2023-11-04 06:41:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!