data class Tut(
var title:String,
var courses:Int,
var author:String,
var category:String
)
定义数据类 Tut 来描述课程对象,包含一些课程的特性。
var tuts = listOf(
Tut("angular base",10,"zidea","web"),
Tut("vue base",10,"rob","web"),
Tut("golang base",30,"zidea","web"),
Tut("rust base",120,"tina","native"),
Tut("kotlin base",50,"jerry","mobie"),
Tut("groovy base",60,"tony","tool")
)
var webTuts = ArrayList()
for(tut in tuts){
if(tut.category == "web"){
webTuts.add(tut)
}
}
for(tut in webTuts){
println(tut.component1())
}
做应用尤其是 web 应用大多数时候都是数据打交道,获取数据,查找数据更新数据。这里用 list 来模拟一个table ,table 中包含一些课程记录供我们使用。然后用 java 思路来进行查找我们想要数据,也就是要找 category 为 web 的课程。
fun getWebTuts(tuts:List):ArrayList{
var webTuts = ArrayList()
for(tut in tuts){
if(tut.category == "web"){
webTuts.add(tut)
}
}
return webTuts
}
进一步整理为一个 getWebTuts 方法,我们也可以扩充为 category 的值可以作为参数来传入到函数中使用。
var webTuts = getWebTuts(tuts)
for(tut in webTuts){
println(tut.component1())
}
好,又有新的需求了就是要找课时少于 100 的课程。
fun getTutlessThen100(tuts:List):ArrayList{
var result = ArrayList()
for(tut in tuts){
if(tut.courses < 100){
result.add(tut)
}
}
return result
}
var webTuts = getWebTuts(tuts)
for(tut in webTuts){
println(tut.component1())
}
var coursesLessThen100Tuts = getTutlessThen100(tuts)
for(tut in coursesLessThen100Tuts){
println(tut.title)
}
如何从无休无尽的需求中解放出来呢,
行为参数化
- 把筛选的行为(函数)作为参数传递到过滤器里面
- 整洁代码,提高效率
需求
- 找出课程数最多的课程
println(tuts.maxBy { it.courses })
Tut(title=rust base, courses=120, author=tina, category=native)
println(tuts.filter {
(it.courses == 10) and (it.category == "web")
})
[Tut(title=angular base, courses=10, author=zidea, category=web), Tut(title=vue base, courses=10, author=rob, category=web)]
Map
println(tuts.map {
"${it.title} by ${it.author}"
})
Any
判断集合中是否有某个数据
println(tuts.any {
it.courses == 120
})
Count
println(tuts.count {
it.courses > 10
})
#### groupBy
```kotlin
println(tuts.groupBy {
it.category
})
{web=[Tut(title=angular base, courses=10, author=zidea, category=web), Tut(title=vue base, courses=10, author=rob, category=web), Tut(title=golang base, courses=30, author=zidea, category=web)], native=[Tut(title=rust base, courses=120, author=tina, category=native)], mobie=[Tut(title=kotlin base, courses=50, author=jerry, category=mobie)], tool=[Tut(title=groovy base, courses=60, author=tony, category=tool)]}
println(tuts.groupBy {
it.category
}.get("web")?.forEach{
println("${it.title}")
})