今天的內(nèi)容是Kotlin過(guò)濾器,首先我們打開(kāi)REPL
首先是一個(gè)簡(jiǎn)單的:
val decorations = listOf("rock","pagoda","plastic plant","alligator","flowerpot")
println(decorations.filter{true})
這將會(huì)輸出所有元素
接下來(lái):
println(decorations.filter { it[0]=='p' })
將會(huì)輸出所有首字母為‘p’的元素
這里有一個(gè)小細(xì)節(jié)胸梆,和其它語(yǔ)言相同敦捧,字符使用單引號(hào)须板,字符串使用雙信號(hào)
過(guò)濾器用在list上,并且返回一個(gè)新的list
接下來(lái)講了一種新的數(shù)據(jù)集合-sequence,sequence每次只能訪(fǎng)問(wèn)一個(gè)條目(元素)兢卵,從第一個(gè)元素開(kāi)始到最后一個(gè)元素結(jié)束习瑰。如果我們使用asSequence,那么將不會(huì)產(chǎn)生一個(gè)新的list秽荤,而是一個(gè)sequence.當(dāng)我們?cè)L問(wèn)sequence中的元素時(shí)甜奄,結(jié)果將會(huì)返回:
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窃款,來(lái)逐次輸出:
var lazyMap = decorations.asSequence().map {
println("map:$it")
it
}
因?yàn)槭莑azy的课兄,所以這里不會(huì)輸出(lazy的意思是只有需要了才會(huì)去執(zhí)行操作)
所以當(dāng)我們輸出第一個(gè)元素的時(shí)候:
println("first:${lazyMap.first()}")
上面的“map”也輸出了(因?yàn)樾枰谝粋€(gè)元素,所以只訪(fǎng)問(wèn)了第一個(gè)元素晨继,如果我們輸出所有元素烟阐,那么也會(huì)遍歷所有元素)
接下來(lái)是練習(xí)題:
這次的練習(xí)題在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.
不得不說(shuō)這次的題我是沒(méi)做出來(lái)(也許是沒(méi)聽(tīng)懂踱稍?)
索性看了下參考答案曲饱,再做解釋?zhuān)?/p>
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')}
哇,視頻里沒(méi)講過(guò)珠月,不過(guò)好歹有提示扩淀,在IDEA中,我們每次打完句點(diǎn)以后啤挎,都會(huì)給出提示可以作為參考