//声明数据类
data class Apple(var id: Int?, var name: String?, var money: BigDecimal?, var num: Int?) {
constructor() : this(null, null, null, null)
fun getMe() = this
fun getMoney() = money!!.toDouble()
}
fun main() {
val appleList = ArrayList<Apple>() //存放apple对象集合
val apple1 = Apple(1, "苹果1", BigDecimal("3.25"), 10)
val apple12 = Apple(1, "苹果2", BigDecimal("1.35"), 20)
val apple2 = Apple(2, "香蕉", BigDecimal("2.89"), 30)
val apple3 = Apple(3, "荔枝", BigDecimal("9.99"), 40)
//添加值
appleList.add(apple1)
appleList.add(apple12)
appleList.add(apple2)
appleList.add(apple3)
//分组
appleList.also { println("分组:") }.groupBy(Apple::id, Apple::getMe).forEach {
(t, u) -> println("\t$t -> $u")
}
//List转Map
appleList.also { println("List转Map:") }.associateBy { it.id }.forEach { (t, u) ->
println("\t$t -> $u")
}
//过滤Filter
appleList.also { println("过滤Filter:") }.filter { it.name != "香蕉" }.forEach { println("\t$it") }
//求和
println("\t 总金额为:${appleList.also { println("求和:") }.sumByDouble { it.getMoney() }}元")
//最值(按照数量比较)
println("最大值:" + appleList.maxWith(kotlin.Comparator { o1, o2 -> if (o1.num!! > o2.num!!) 1 else -1 }))
println("最小值:" + appleList.minWith(kotlin.Comparator { o1, o2 -> if (o1.num!! > o2.num!!) 1 else -1 }))
//去重(除去id重复的数据)
appleList.also { println("去重") }.distinctBy { it.id }.forEach { println("\t $it") }
}
Kotlin-Stream01
最新推荐文章于 2023-12-25 18:37:25 发布