在Kotlin中按多个字段排序收集
比方说,我有一个人名列表,我需要首先按年龄,然后按名称排序。
来自C#的背景,我可以通过使用LINQ轻松实现这种语言:
var list=new List<Person>(); list.Add(new Person(25, "Tom")); list.Add(new Person(25, "Dave")); list.Add(new Person(20, "Kate")); list.Add(new Person(20, "Alice")); //will produce: Alice, Kate, Dave, Tom var sortedList=list.OrderBy(person => person.Age).ThenBy(person => person.Name).ToList();
如何使用Kotlin完成这个工作?
这是我试过的(这显然是错误的,因为第一个“sortedBy”子句的输出被第二个输入覆盖,导致列表按名称排序)
val sortedList = ArrayList(list.sortedBy { it.age }.sortedBy { it.name })) //wrong
sortedWith
+ compareBy
(采用可变compareBy
的lambda表达式)诀窍:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
您还可以使用更简洁的可调用参考语法:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
使用sortedWith
对Comparator
sortedWith
进行排序。
然后你可以用几种方法构造一个比较器:
-
compareBy
,thenBy
在调用链中构造比较器:list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
-
compareBy
有一个重载函数,它有多个函数:list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
- 如何将主键作为Room Persistence lib的自动增量
- Kotlin库'rxkotlin-0.21.0.jar'具有不受支持的格式。 请更新库或插件
- Firebase Perf不会运行测试应用程序:transformClassesWithFirebasePerformancePluginForDebugAndroidTest
- 使用kapt Android Studio进行注释处理
- 你如何为MediaPlayer声明一个全局变量?
- 在Kotlin Realm Extention中如何解决“功能不属于这个领域的模式的一部分”
- 使用伴随对象在Kotlin中返回类的一个实例
- MutableLiveData与Kotlin多重打样器通用不工作
- 继承内部java类的问题