kotlin集合操作符——总数操作符
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                kotlin集合操作符——总数操作符
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                目錄
any
all
count
fold
foldRight
forEach
forEachIndexed
max
maxBy
min
minBy
none
reduce
reduceRight
sumBy
關于集合的操作符,直接引用書上的內容,基本上總結的很好了。
any
如果至少有一個元素符合給出的判斷條件,則返回true。
val list = listOf(1, 2, 3, 4, 5, 6) assertTrue(list.any { it % 2 == 0 }) assertFalse(list.any { it > 10 })all
如果全部的元素符合給出的判斷條件,則返回true。
assertTrue(list.all { it < 10 }) assertFalse(list.all { it % 2 == 0 })count
返回符合給出判斷條件的元素總數。
assertEquals(3, list.count { it % 2 == 0 })fold
在一個初始值的基礎上從第一項到最后一項通過一個函數累計所有的元素。
assertEquals(25, list.fold(4) { total, next -> total + next })foldRight
與fold一樣,但是順序是從最后一項到第一項。
assertEquals(25, list.foldRight(4) { total, next -> total + next })forEach
遍歷所有元素,并執行給定的操作。
list.forEach { println(it) }forEachIndexed
與forEach,但是我們同時可以得到元素的index。
list.forEachIndexed { index, value-> println("position $index contains a $value") }max
返回最大的一項,如果沒有則返回null。
assertEquals(6, list.max())maxBy
根據給定的函數返回最大的一項,如果沒有則返回null。
// The element whose negative is greater assertEquals(1, list.maxBy { -it })min
返回最小的一項,如果沒有則返回null。
assertEquals(1, list.min())minBy
根據給定的函數返回最小的一項,如果沒有則返回null。
// The element whose negative is smaller assertEquals(6, list.minBy { -it })none
如果沒有任何元素與給定的函數匹配,則返回true。
// No elements are divisible by 7 assertTrue(list.none { it % 7 == 0 })reduce
與fold一樣,但是沒有一個初始值。通過一個函數從第一項到最后一項進行累計。
assertEquals(21, list.reduce { total, next -> total + next })reduceRight
與reduce一樣,但是順序是從最后一項到第一項。
assertEquals(21, list.reduceRight { total, next -> total + next })sumBy
返回所有每一項通過函數轉換之后的數據的總和。
assertEquals(3, list.sumBy { it % 2 })?
總結
以上是生活随笔為你收集整理的kotlin集合操作符——总数操作符的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: kotlin学习笔记——扩展函数(ank
- 下一篇: kotlin集合操作符——过滤操作符
