集合
1、使用數組
arrayOf ,并使用Array類中的屬性與方法來處理他們內部的值
java中:
String [] strings = new String[4];
strings[0] = "an";
strings[1] = "array";
strings[2] = "of";
strings[3] = "strings";
//或者
strings = "an array of strings".split(" ");
kotlin中:
val strings = arrayOf("this","is","an","array","of","strings")
arrayOfNulls創建僅包含空值的數組,必須指定類型
val nullStringArray = arrayOfNulls<String>(5)//一個僅僅包含空值的數組
Array類
val squares = Array(5){i -> (i*i).toString()}
//結果為{"0","1","4","9","16"}的數組
withIndex訪問數組
val strings = arrayOf("this","is","an","array","of","strings")
for((index,value) in strings.withIndex()){
pringln("Index $index maps to $value")
}
Index 0 maps to this
Index 1 maps to is
Index 2 maps to an
Index 3 maps to array
Index 4 maps to of
Index 5 maps to strings
2、創建集合
不可變的集合:listOf、setOf、mapOf
可變版本:mutableListOf、mutableSetOf、mutableMapOf
var numList = listOf(3,1,4,1,5,9)
var numSet = setOf(3,1,4,1,5,9)//numSet.size == 5
var map = mapOf(1 to "one",2 to "two",3 to "three")
var numList = mutableListOf(3,1,4,1,5,9)
var numSet = mutableSetOf(3,1,4,1,5,9)
var map = mutableMapOf(1 to "one",2 to "two",3 to "three")
3、為已存在的集合創建只讀視圖
如何為現有可變list/map/set創建只讀版本。
將值賦值給List、Set、Map即可
val muNums = mutableListOf(3,1,4,1,5,9)
val onlyReadNum :List<Int> = muNums .toList()
該方法創建了一個單獨的對象,內容相同但不代表是相同對象。
如果想要一個相同對象的只讀視圖,將可變list賦值給一個List類的引用即可:
val readOnlySameList :List<Int> = muNums
如果指向的list被修改,只讀視圖也會顯示修改后的值。
4、從集合構建map
如何通過每個鍵生成,鍵值關聯起來的map?
associateWith函數
val keys = 'a'..'f'
val map = key.associateWith{it to it.toString().repeat(5).capitalize()}
println(map)
{a=(a, Aaaaa), b=(b, Bbbbb), c=(c, Ccccc), d=(d, Ddddd), e=(e, Eeeee), f=(f, Fffff)}
//如果是老版本的kotlin輸出如下
{a=Aaaaa, b=Bbbbb, c=Ccccc, d=Ddddd, e=Eeeee, f=Fffff}
在kotlin 1.3中的associateWith簡化了代碼,生成了String值,而不是生成Pair<Char,String>
val keys = 'a'..'f'
val map = key.associateWith{it.toString().repeat(5).capitalize()}
println(map)
{a=Aaaaa, b=Bbbbb, c=Ccccc, d=Ddddd, e=Eeeee, f=Fffff}
5、當集合為空的時候返回默認值
使用ifEmpty 和ifBlank
data class Product(val name:String,
val price:Double,
val onSale:Boolean = false)
// val products = listOf(pA,pB,pC)
val products = listOfNotNull<Product>()
println(nameOfP1(products))
fun nameOfP1(products :List<Product>) =
products.filter{it.onSale}
.map{it.name}
.joinToString(separator = ",")
fun nameOfP2(products :List<Product>) =
products.filter{it.onSale}
.map{it.name}
.ifEmpty{listOf("none")} //默認空集合
.joinToString(separator = ",")
fun nameOfP3(products :List<Product>) =
products.filter{it.onSale}
.map{it.name}
.joinToString(separator = ",")
.ifEmpty{"none"} //默認空字符串
1結果只是換行了
23結果會輸出none
6、將變量限制在給定區間
給定一個值,在區間內返回本身,在區間外返回最小值和最大值。
使用coerceIn函數,并傳入最小值和最大值。
val range = 3..8
println(5.coerceIn(range)) //5
println(5.coerceIn(3,8)) //5
println(1.coerceIn(range)) //3
println(1.coerceIn(3,8)) //3
7、處理集合中的窗口
chunked:將集合切分為相同部分
windowed:將塊沿集合滑動給定間隔的塊
chunked,切分集合為一個包含list的list,每個列表都具有給定大小或更小
fun main() {
val range = 0..10
val chunked = range.chunked(3)
println("chunked="+chunked)
//chunked=[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
val chunked2 = range.chunked(3){it.average()}
println("chunked2="+chunked2)
//chunked2=[1.0, 4.0, 7.0, 9.5]
}
chunked函數其實是windowed函數的特殊情況
windowed函數接收3個函數 size(每個窗口的元素數量)、step(每一步向前移動的元素數,默認1)、partialwindows(默認false,如果沒有足夠數量,是否保留最后一部分)
chunked(size:Int) ->return windowed(size,size,true)
8、解構list
解構是通過將對象的值分配給變量的集合來從中提取值的過程。
val list = listOf("a","b","c","d","e","f","g")
val (a,b,c,d,e) = list
println("$a $b $c $d $e")
//a b c d e
列表創建的前五個元素已經分配給了相同名稱變量。之所以可行是因為List類具有名為componentN的標準庫中定義的擴展函數,其中N從1到5.
9、將多個屬性排序
sortedWith / compareBy
data class Golfer(val score:Int,val first:String,val last:String)
fun main() {
val golfers = listOf(
Golfer(70,"jack","nicklaus"),
Golfer(68,"tom","watson"),
Golfer(68,"bubba","watson"),
Golfer(70,"tiger","woods"),
Golfer(68,"ty","webb"),
)
//score > lastname > first name
val sorted = golfers.sortedWith(
compareBy({it.score},{it.last},{it.first})
)
sorted.forEach{println(it)}
}
->
Golfer(score=68, first=bubba, last=watson)
Golfer(score=68, first=tom, last=watson)
Golfer(score=68, first=ty, last=webb)
Golfer(score=70, first=jack, last=nicklaus)
Golfer(score=70, first=tiger, last=woods)
另一種方式是使用thenBy
val comparator = compareBy<Golfer>(Golfer::score)
.thenBy(Golfer::last)
.thenBy(Golfer::first)
golfers.sortedWith(comparator )
.forEach(::printLn)
10、自定義迭代器
11、根據類型過濾集合
filterIsInstance / filterIsInstanceTo
kotlin集合中包含一個filter的擴展函數,接受一個可以用來提取滿足任何布爾條件的元素謂詞作為參數
val list = listOf("a",LocalDate.now(),3,1,4,"b")
val strings = list.filter{it is String}
for(s in strings){
s.length//不編譯,類型被刪除
}
盡管過濾有效,但推定類型為List<Any>因此不會轉換為String.
可以添加filterIsInstance
val list = listOf("a",LocalDate.now(),3,1,4,"b")
val all= list.filterIsInstance<Any>()
val strings= list.filterIsInstance<String>()
val ints= list.filterIsInstance<Int>()
val datas= list.filterIsInstance<LocalDate::class.java>()
all -> list
strings ->"a","b"
ints - > 1,3,4
dates -> LocalDate.now()
filterIsInstance 返回類型是List<R>
filterIsInstanceTo返回類型是MutableCollection<inR>
val list = listOf("a",LocalDate.now(),3,1,4,"b")
val all= list.filterIsInstanceTo(mutableListOf())
val strings= list.filterIsInstanceTo(mutableListOf<String>())
val ints= list.filterIsInstanceTo(mutableListOf<Int>())
val datas= list.filterIsInstanceTo(mutableListOf<LocalDate>())
12、在數列中創建區間
kotlin使用雙點操作符可以創建區間如1..5,創建一個IntRange。kotlin的區間都是閉區間,即包含兩個端點。
import java.time.LocalDate
fun main() {
val started = LocalDate.now()
val mid = started.plusDays(3)
val end = started.plusDays(5)
val dataRange = started..end
println(started in dataRange)//t
println(mid in dataRange)//t
println(end in dataRange)//t
println(started.minusDays(1) in dataRange)//f
}
一旦嘗試在區間進行迭代,會有編譯錯誤
for(date in dateRange) println(it)//編譯錯誤
問題在于區間而不在于數列,自定義數列實現了iterable接口
需要自定義Iterator,接口覆蓋next和hasNext