Kotlin higher-order functions (on)

  • maxby/minby
  • filter
  • map
  • any

Higher-order functions: to function as a parameter, this function is called higher-order functions, functional programming refers to such highly abstract programming paradigm.
In Kotlin, there are a number of higher-order functions, it can help us simplify the code, reducing the amount of code to achieve the desired functionality. Next, I will list a few common higher-order functions and source code analysis to understand and easy to remember.

maxby/minby

As the name suggests, maxby minby methods and maximum and minimum values is determined. Normally, in Java, we are determined in this way the maximum and minimum (general method)
assumes that the database dogdatabase, internal contains data:

data class dog(var name:String,var kind:String,var hight:Int,var address:String)
var dogdatabase= listOf<dog>(
        dog("妞妞","萨摩耶",23,"北京"),dog("阿贵","田园犬",22,"伊拉克"),
        dog("二哈","哈士奇",21,"上海"),dog("撒狗","田园犬",6,"新疆"),
        dog("小Q","柴犬",15,"北京"),dog("卤蛋","贵宾犬",21,"新疆"),
        dog("妞妞1","不丹",14,"广州"),dog("卤鸡","藏獒",32,"河北"),
        dog("妞妞2","萨摩耶",26,"广州"),dog("冒菜","拉布拉多",44,"河北"),
        dog("老麻","哈士奇",28,"哈尔滨"),dog("阿花","拉布拉多",44,"北京")
    )

Obtained the highest height of the dog

fun main(args:Array<String>){
	var maxheight=0
	for(i in dogdatabase)
	{	
		if(i.height>maxheight)
		{	
			maxheight=i.height
		}
	}
	for(i in dogdatabase)
	{
		if(i.height=maxheight)
		{
			println("身高最高的狗狗是${i.name},身高是${i.height}")
		}
	}
}

Typically, this has become a "fixed format" in the realization of certain functions, in Kotlin, the creators will be implemented as a higher-order functions maxby, we need only look at the following:

fun main(args:Array<String>){                                                 
    //maxby 找最大数                                                     
    var maxhight=dogdatabase.maxBy{it.hight}                                                              
    println(maxhight)                                                
}

This can reduce the amount of code, but there will be a problem, this maxby will only output a maximum value, if we have two values at the same time meet the maximum, then the other value will be ignored.
The following is the source:

public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? {
    val iterator = iterator()
    if (!iterator.hasNext()) return null
    var maxElem = iterator.next()
    if (!iterator.hasNext()) return maxElem
    var maxValue = selector(maxElem)
    do {
        val e = iterator.next()
        val v = selector(e)
        if (maxValue < v) {
            maxElem = e
            maxValue = v
        }
    } while (iterator.hasNext())
    return maxElem
}

The parameters passed to maxby Selector herein, is defined to be an iterator iterator value filter, if hasnext is empty, the parameter passed to Null, returns a null, a maximum value defined next, in an incoming there worthy case, the number of data is divided into the case where the case 1 and greater than 1. If equal to a maximum value is returned directly to the max, if more than one, the pointer does not point in the case where the null pointer backward sequentially comparing data, if imparting greater then the set worth maxElem, returns a final there are a maximum of maxElem collection.
minby principles and maxby similar.

filter

filter is a filter capable of filtering out the data that meets the criteria by a variety of conditions.

println(dogdatabase.filter { it.address=="新疆" && it.kind=="田园犬" })     

You can get the results:

[dog(name=撒狗, kind=田园犬, hight=6, address=新疆)]

Source as follows:

public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
    return filterTo(ArrayList<T>(), predicate)
}

It accepts a (T) -> Boolean type of function return. But it does not perform the operation himself, but to create a new ArrayList as the operation target, and then put this ArrayList and passed into the function package sent filterTo function handles:
filterTo () function through the elements in the array, each element verify whether the predicate function, if they meet just add it to the collection target destination, ie filter function returns true for all elements of incoming function.

map

map will be appreciated that the mapping can be mapped to meet the requirements of the data into an array.
Source as follows:

public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
    return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}

It accepts a (T) -> R type function returns. But does not perform the operation, but will create a new ArrayList as the operation target, and then put this ArrayList and passed into the function package sent mapTo function processing:

public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) -> R): C {
    for (item in this)
        destination.add(transform(item))
    return destination
}

mapto in the incoming item in the screening arraylist, wherein if the item is in, it is added to the corresponding transform destination, after traversing manner destination array result is returned.

So we can use it:

println(dogdatabase.map { "${it.name},${it.kind}"}) 

The map database in the dog's name and the type of display and print the
obtained results:

[妞妞,萨摩耶, 阿贵,田园犬, 二哈,哈士奇, 撒狗,田园犬, 小Q,柴犬, 卤蛋,贵宾犬, 妞妞1,不丹, 卤鸡,藏獒, 妞妞2,萨摩耶, 冒菜,拉布拉多, 老麻,哈士奇, 阿花,拉布拉多]

any

is determined not to have any qualified data in the data, the result is returned to the Boolean type. true or false
source as follows:

public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean {
    if (this is Collection && isEmpty()) return false
    for (element in this) if (predicate(element)) return true
    return false
}

Here, the any receiving one (T) -> Boolean function of the type, operation to be empty sentence, if the incoming returns false predicate is empty,
if not empty, then the loop through Element, is matched to the corresponding data returns true, It does not match the data it returns false
to find whether there is a pastoral dog dog database:

  println(dogdatabase.any{it.kind=="田园犬"}) 
  //得到结果
  true

The next one, will continue to analyze and memories of other higher-order functions.

Published 15 original articles · won praise 3 · Views 342

Guess you like

Origin blog.csdn.net/Py_csdn_/article/details/104765541