天天看點

Kotlin 之 數組和集合篇之集合操作符Kotlin 之 數組和集合篇之集合操作符

Kotlin 之 數組和集合篇之集合操作符

文章目錄

  • Kotlin 之 數組和集合篇之集合操作符
    • 正文
      • 操作符
        • 1. 集合操作符之 map
        • 2. 集合操作符之 zip 合并
        • 3. 集合操作符之 flatten 打平
        • 4. 集合操作符之 字元串操作
        • 5. 集合操作符之過濾操作
        • 6. 集合操作符之加減
        • 7. 集合操作符-flatmap
        • 8. 集合操作符之取集合一部分資料
        • 9. 集合操作符之取單個元素
        • 10. 集合操作符之 order 排序
        • 11. 集合操作符之聚合操作

正文

操作符

1. 集合操作符之 map

//===============map 映射,list、set、map 映射新的 list、set、map
val numbers2 = listOf(1, 2, 1)
println(numbers2.map { it * 3 })
//[1] map 映射,生成新清單
val numbers = setOf(1, 2, 3)
println(numbers.map { it * 3 })
//[2] mapIndex ,可以使用索引值和 value
println(numbers.mapIndexed { idx, value -> value * idx })
//[3] mapNotNull 映射, 生成新清單,會剔除 null
println(numbers.mapNotNull { if ( it == 2) null else it * 3 })

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
//[4] map 的映射,key 改為大寫
println(numbersMap.mapKeys { it.key.toUpperCase() })
//[5] map 的映射,值加上
println(numbersMap.mapValues { it.value + it.key.length })
           

2. 集合操作符之 zip 合并

//============ 雙路合并
val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
//[6] zip 傳回 List<Pair<T, R>>
println(colors zip animals)
//輸出:[(red, fox), (brown, bear), (grey, wolf)]
    
//[7] unzip 傳回 Pair<List<T>, List<R>>
val numberPairs = listOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println(numberPairs.unzip())

           

3. 集合操作符之 flatten 打平

//================= flatten 打平
// [1] flatten 打平多個清單的清單,打平成一個清單
val numberSets = listOf(setOf(1, 2, 3), setOf(4, 5, 6), setOf(1, 2))
println(numberSets.flatten())
           

4. 集合操作符之 字元串操作

//================ 字元串
//[1] 清單轉成字元串輸出
val numbersStr = listOf("one", "two", "three", "four")
println(numbersStr) //輸出: [one, two, three, four]
println(numbersStr.joinToString()) //輸出:one, two, three, four

//[2] 清單添加到字元串後面
val listString = StringBuffer("The list of numbers: ")
numbersStr.joinTo(listString)
println(listString) //輸出: The list of numbers: one, two, three, four

//[3] 清單添加轉字元串,修改分隔符、字元串字首和字尾
val numbers3 = listOf("one", "two", "three", "four")
println(numbers3.joinToString(separator = " | ", prefix = "start: ", postfix = ": end"))
//輸出:start: one | two | three | four: end

//[4] 增加截斷
val numbers4 = (1..100).toList()
println(numbers4.joinToString(limit = 10, truncated = "...", postfix = "end"))
//輸出:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...end
           

5. 集合操作符之過濾操作

//[1] filter操作符,對于list 和 set 傳回符合條件的 list
val numbers = listOf("one", "two", "three", "four")
val longerThan3 = numbers.filter { it.length > 3 }
println(longerThan3)
//輸出:[three, four]

//[2] filter操作符,對于list 和 set 傳回符合條件的 map
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
println(filteredMap)

val numbers3 = listOf("one", "two", "three", "four")
//[3] 增加 index 的篩選
val filteredIdx = numbers3.filterIndexed { index, s -> (index != 0) && (s.length < 5)  }
println(filteredIdx)

//[4] 剛好和 filter 相反
val filteredNot = numbers3.filterNot { it.length <= 3 }
println(filteredNot)

//[5] 篩選類型
val numbers5 = listOf(null, 1, "two", 3.0, "four")
println("All String elements in upper case:")
numbers5.filterIsInstance<String>().forEach {
    println(it.toUpperCase())
}

//[6] 劃分,傳回 Pair<List<T>, List<T>>
val numbers6 = listOf("one", "two", "three", "four")
val (match, rest) = numbers6.partition { it.length > 3 }
println(match)
println(rest)

val numbers7 = listOf("one", "two", "three", "four")
//[7] 條件是否滿足
println(numbers7.any { it.endsWith("e") })//至少一個滿足條件,true
println(numbers7.none { it.endsWith("a") })//是否沒有存在,true
println(numbers7.all { it.endsWith("e") })//都滿足,false

           

6. 集合操作符之加減

val numbers = listOf("one", "two", "three", "four")
//[1] 清單操作符重載
val plusList = numbers + "five"
println(plusList)
//輸出:[one, two, three, four, five]
val minusList = numbers - listOf("three", "four")
println(minusList)
//輸出:[one, two]
           

7. 集合操作符-flatmap

- flatmap: 周遊每個元素,并未每個元素建立新的集合,最好合并到一個集合中
- 
intArray.flatMap { i -> listOf("${i+1}", "a") }.forEach { print(it+" ") }
    //列印 2 a 3 a 4 a 
           

8. 集合操作符之取集合一部分資料

//[1] slic 切片,取個子清單,slice 當 for 語句,放range 參數
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.slice(1..3))
println(numbers.slice(0..4 step 2))
println(numbers.slice(setOf(3, 5, 0)))

//[2] take\drop 從清單取子清單
val numbers2 = listOf("one", "two", "three", "four", "five", "six")
println(numbers2.take(3))//前三,[one, two, three]
println(numbers2.takeLast(3))//後三
println(numbers2.drop(1))//剔除前面一個
println(numbers2.dropLast(5))//剔除後面五個

// [3] 帶條件的擷取
val numbers3 = listOf("one", "two", "three", "four", "five", "six")
println(numbers3.takeWhile { !it.startsWith('f') })//剔除 f 開頭
println(numbers3.takeLastWhile { it != "three" })
println(numbers3.dropWhile { it.length == 3 })//剔除三個長度的
println(numbers3.dropLastWhile { it.contains('i') })//剔除five\six

//[4] chunked ,将清單按指定 size 分成多個 清單
val numbers4 = (0..13).toList()
println(numbers4.chunked(3))
//輸出:[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13]]

//[5] 不說了,看輸出
val numbers5 = listOf("one", "two", "three", "four", "five")
println(numbers5.windowed(3))
//輸出:[[one, two, three], [two, three, four], [three, four, five]]

           

9. 集合操作符之取單個元素

//[1] 取任意個數,0 ~ size -1
val numbers = linkedSetOf("one", "two", "three", "four", "five")
println(numbers.elementAt(3))

val numbersSortedSet = sortedSetOf("one", "two", "three", "four")
println(numbersSortedSet.elementAt(0)) //four

//[2] 取第一個,最好一個
val numbers3 = listOf("one", "two", "three", "four", "five")
println(numbers3.first())
println(numbers3.last())

// [3] 有異常就傳回 null
//    println(numbers.elementAt(5)) //越級會報錯
println(numbers.elementAtOrNull(5)) //有異常就傳回 null

//[4] 帶條件的取資料
val numbers4 = listOf("one", "two", "three", "four", "five", "six")
println(numbers4.first { it.length > 3 })//three
println(numbers4.last { it.startsWith("f") })//five

// [5] 沒有條件不傳回異常,傳回 null
val numbers5 = listOf("one", "two", "three", "four", "five", "six")
println(numbers5.firstOrNull { it.length > 6 })

//[5] 換湯不換藥的 find
val numbers6 = listOf(1, 2, 3, 4)
println(numbers6.find { it % 10 == 0 })//= firstOrNull
println(numbers6.findLast { it % 10 == 0 })//= lastOrNull

//[6] 是否為空,是否不為空
val empty = emptyList<String>()
println(empty.isEmpty())
println(empty.isNotEmpty())
           

10. 集合操作符之 order 排序

//[1] 使用 order 排序
println(listOf("aaa", "bb", "c").sortedWith(compareBy { it.length }))
//輸出:[c, bb, aaa]

val numbers = listOf("one", "two", "three", "four")
//[2] 自然序列,反序列
println("Sorted ascending: ${numbers.sorted()}")
println("Sorted descending: ${numbers.sortedDescending()}")

//[3] 倒序,傳回新清單,原序列修改不影響倒序清單
val numbers3 = listOf("one", "two", "three", "four")
println(numbers3.reversed())

//[4] 原序列修改會影響倒序清單
val numbers4 = mutableListOf("one", "two", "three", "four")
val reversedNumbers = numbers4.asReversed()
println(reversedNumbers)
numbers4.add("five")
println(reversedNumbers)

           

11. 集合操作符之聚合操作

val numbers = listOf(6, 42, 10, 4)
//[1] 傳回集合個數,最大,最小,平均數,總數
println("Count: ${numbers.count()}")
println("Max: ${numbers.max()}")
println("Min: ${numbers.min()}")
println("Average: ${numbers.average()}")
println("Sum: ${numbers.sum()}")

//[2] 最小的且符合條件。如最小的且是能被 3 整除
val numbers2 = listOf(5, 42, 10, 4)
val min3Remainder = numbers2.minBy { it % 3 }
println(min3Remainder)

//[3] 取最大值,排序方式按字元串長度
val strings = listOf("one", "two", "three", "foura")
val longestString = strings.maxWith(compareBy { it.length })
println(longestString)

val numbers4 = listOf(5, 42, 10, 4)
println(numbers4.sumBy { it * 2 })
println(numbers4.sumByDouble { it.toDouble() / 2 })

val numbers5 = listOf(5, 2, 10)

// [5] 簡化操作,這裡是累加。 reduce 和 fold 差別就是 fold有初始化
val sum = numbers5.reduce { sum, element -> sum + element }
println(sum)
val sumDoubled = numbers5.fold(0) { sum, element -> sum + element * 2 }
println(sumDoubled)