3、Kotlin过滤器

今天的内容是Kotlin过滤器,首先我们打开REPL
首先是一个简单的:

val decorations = listOf("rock","pagoda","plastic plant","alligator","flowerpot")
println(decorations.filter{true})

这将会输出所有元素
接下来:

println(decorations.filter { it[0]=='p' })

将会输出所有首字母为‘p’的元素
这里有一个小细节,和其它语言相同,字符使用单引号,字符串使用双信号
过滤器用在list上,并且返回一个新的list

接下来讲了一种新的数据集合-sequence,sequence每次只能访问一个条目(元素),从第一个元素开始到最后一个元素结束。如果我们使用asSequence,那么将不会产生一个新的list,而是一个sequence.当我们访问sequence中的元素时,结果将会返回:

fun eagerExample(){
    val decorations = listOf("rock","pagoda","plastic plant","alligator","flowerpot")
    val eager = decorations.filter { it[0]=='p' }
    println(eager)
    var filtered = decorations.asSequence().filter { it[0]=='p' }
    println(filtered.toList())
}

为了弄清sequence是什么,我们使用了map,来逐次输出:

var lazyMap = decorations.asSequence().map {
        println("map:$it")
        it
    }

因为是lazy的,所以这里不会输出(lazy的意思是只有需要了才会去执行操作)
所以当我们输出第一个元素的时候:

println("first:${lazyMap.first()}")

上面的“map”也输出了(因为需要第一个元素,所以只访问了第一个元素,如果我们输出所有元素,那么也会遍历所有元素)

接下来是练习题:
这次的练习题在REPL中完成。
Create a list of spices, as follows:
val spices = listOf("curry", "pepper", "cayenne", "ginger", "red curry", "green curry", "red pepper" )
Create a filter that gets all the curries and sorts them by string length.
Hint: After you type the dot (.), IntelliJ will give you a list of functions you can apply.
Filter the list of spices to return all the spices that start with 'c' and end in 'e'. Do it in two different ways.
Take the first three elements of the list and return the ones that start with 'c'.

Note: We will be able to do a lot more interesting stuff with filters after you learn about classes and Map.

不得不说这次的题我是没做出来(也许是没听懂?)
索性看了下参考答案,再做解释:

spices.filter { it.contains("curry") }.sortedBy { it.length }
spices.filter{it.startsWith('c')}.filter{it.endsWith('e')}
spices.filter { {it.startsWith('c') && it.endsWith('e') }
spices.take(3).filter{it.startsWith('c')}

哇,视频里没讲过,不过好歹有提示,在IDEA中,我们每次打完句点以后,都会给出提示可以作为参考

你可能感兴趣的:(3、Kotlin过滤器)