Kotlin高阶函数(下)

  • count
  • find
  • groupBy

count

count用来统计符合条件的数据的个数
首先来看它的源码:

public inline fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int {
    if (this is Collection && isEmpty()) return 0
    var count = 0
    for (element in this) if (predicate(element)) checkCountOverflow(++count)
    return count
}

count函数传入一个(T) -> Boolean类型的函数,返回值为Int类型也就是count的值。如果集合为空则直接返回0,如果不为空则遍历该集合,将符合条件的数据筛选出来,每符合一条,count+1最后返回count值。
应用:

dogdatabase.count{it.height==44}
//得到结果为2

可以说kotlin中的高阶函数对于新手还是非常友好的,省去了很多代码量去构建这些常用的功能。让我们把更多的精力放到攻坚的地方上去。

find

查找符合条件并返回第一个符合该条件的数据。
源码如下:

public inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T? {
    for (element in this) if (predicate(element)) return element
    return null
}

该函数接收一个(T) -> Boolean类型的函数参数,predicat接受一个输入参数并返回一个布尔值类型的值。如果该值为true,则符合查找条件,返回这个element,这和filter的区别在于,filter把所有符合条件的都加入到destination中一并返回,而只将遇到的第一个符合条件的element返回。

dogdatabase.find { it.hight==44 }
//得到一个结果 冒菜

groupBy

分组
源码如下:
groupBy的源码:

public inline fun <T, K> Iterable<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>> {
    return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
}

groupBy中groupByTo的源码:

public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K): M {
    for (element in this) {
        val key = keySelector(element)
        val list = destination.getOrPut(key) { ArrayList<T>() }
        list.add(element)
    }
    return destination
}

groupByTo中getorPut的源码:

public inline fun <K, V> MutableMap<K, V>.getOrPut(key: K, defaultValue: () -> V): V {
    val value = get(key)
    return if (value == null) {
        val answer = defaultValue()
        put(key, answer)
        answer
    } else {
        value
    }
}

让我们来梳理一下这个groupBy的逻辑,函数接受一个(T) -> K类型的参数,返回值为一个Map包含一个Key值和一个List的value.将传入的参数送至groupByTo中,循环遍历,将每一组数据的key值提取出来后创建一个list来存符合key值得数据,在getorPut函数中,这里面我不太懂…求大佬告诉… 然后得出了符合条件的值并存入至list,最后返回一个Map

dogdatabase.groupBy { it.kind }
//得到结果
{萨摩耶=[dog(name=妞妞, kind=萨摩耶, hight=23, address=北京), dog(name=妞妞2, kind=萨摩耶, hight=26, address=广州)], 田园犬=[dog(name=阿贵, kind=田园犬, hight=22, address=伊拉克), dog(name=撒狗, kind=田园犬, hight=6, address=新疆)], 哈士奇=[dog(name=二哈, kind=哈士奇, hight=21, address=上海), dog(name=老麻, kind=哈士奇, hight=28, address=哈尔滨)], 柴犬=[dog(name=小Q, kind=柴犬, hight=15, address=北京)], 贵宾犬=[dog(name=卤蛋, kind=贵宾犬, hight=21, address=新疆)], 不丹=[dog(name=妞妞1, kind=不丹, hight=14, address=广州)], 藏獒=[dog(name=卤鸡, kind=藏獒, hight=32, address=河北)], 拉布拉多=[dog(name=冒菜, kind=拉布拉多, hight=44, address=河北), dog(name=阿花, kind=拉布拉多, hight=44, address=北京)]}

听说…Java中lamabda都有

发布了15 篇原创文章 · 获赞 3 · 访问量 340

猜你喜欢

转载自blog.csdn.net/Py_csdn_/article/details/104786242