首页 > 编程知识 正文

kotlin遍历集合

时间:2023-05-05 18:38:05 阅读:276812 作者:4128

1、Kotlin的集合排序

        如果我们需要对一个集合里面的某个对象的一个字段进行排序,java的话需要实现一个比较器Comparator,Kotlin的针对集合里面的某个对象的一个字段进行排序非常简单,一行代码搞定。

2、sortBy方法、sortByDescending方法

1)、sortBy升序排列

2)、sortByDescending降序排列

测试代码如下

data class Student(var name: String, var age: Int, var score: Int) { override fun toString(): String { return "Student(name='$name', age=$age, score=$score)" }} var list = mutableListOf<Student>() list.add(Student("chenyu3", 23, 100)) list.add(Student("chenyu4", 24, 98)) list.add(Student("chenyu1", 21, 97)) list.add(Student("chenyu2", 22, 98)) list.add(Student("chenyu2", 20, 99)) list.forEach { Log.d("chenyu", "${it}") } println("-------

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。