kotlin lambda 集合

来源:互联网 发布:红外光谱数据库下载 编辑:程序博客网 时间:2024/06/06 14:19
import javax.swing.plaf.SeparatorUI/** * Created by gacmy on 2017/6/15. *//**lamba 表达是的应用1* button.setOnClickListener(new OnClickListener(){*   @Override*   public void onClick(View view){*       //action on click*   }* }* };**使用lamba表达式以后 button.setOnclickListener{//action on click}* *///找出person类集合最大的年纪data class Person(val name: String,val age: Int)fun findTheOldest(people: List<Person>){    var maxAge = 0    var theOldest: Person? = null    for(person in people){        if(person.age > maxAge){            maxAge = person.age            theOldest = person        }    }    println(theOldest)}fun test(){    val people = listOf(Person("Alice",29),Person("Bob",31))    findTheOldest(people)    //使用库函数    println(people.maxBy { it.age })    //lamaba 仅仅代理一个方法或者属性,他可以被成员的引用代替    println(people.maxBy (Person::age ))    //lambda 格式的调用    people.maxBy({p: Person -> p.age})    //如果lambda参数式最后一个参数可以写在函数体外面    people.maxBy (){person -> person.age }    //lambda 式唯一的一个参数 可以省略参数括号    people.maxBy { p: Person -> p.age }}//lambda 表达式的语法 { x: Int,y: Int -> x+y }  lambda表达式在大括号里面 箭头分割参数列表和函数体fun testLambda(){//可以将lambda表达式赋值给一个变量 这个变量可以作为函数使用    val sum = {x: Int, y:Int -> x+y }    println(sum(1,2))    //run{  println(42) }()    val people = listOf(Person("Alice",29),Person("Bob",31))    val names = people.joinToString(separator = " ",transform = {p: Person -> p.name})    println(names)    //lambda 最后一个参数可以写在圆括号外面    people.joinToString(" "){p: Person -> p.name}    //it 代表这个对象的本身 最好用在清楚的参数类型的时候 不要用在嵌套的lambda 表达式中    people.joinToString(" "){it.name}    //:: 成员引用符号    //下面可以使用:: 这种写法 我也不太清楚    val getName = Person::name    people.joinToString(separator = " ",transform = (getName))    val getAge = {person: Person -> person.age}    people.maxBy(Person::age)    people.maxBy(getAge)    //::可以引用函数的引用    fun salute()= println("salute")    run(::salute)    //:: 代表构造函数引用    val createPerson = ::Person    val p = createPerson("alice",20)    println(p)    //:: 代表扩展函数的引用    fun Person.isAdult() = age >= 20    val predicate = Person::isAdult}fun testFunReference(){    //函数引用 kotilin1.0 调用方法引用 属性引用需要传递对象实例    val p = Person("Dimitry",34)    val personsAgeFun =Person::age    println(personsAgeFun(p))    //kotiln1.1 允许使用对象的实例    val dimitryAgeFun = p::age    println(dimitryAgeFun())}fun printMessageWithPrefix(messages: Collection<String>, prefix: String){    { messages.forEach{ println("$prefix $it")}}}fun testPrintMessageWithPrefix(){    val errors = listOf("403 Forbidden","404 Not Found")    printMessageWithPrefix(errors,"Error:")}//lambda 可以访问修改变量 非finalfun printProblemCounts(response: Collection<String>){    var clientErrors = 0;    var serverErrors = 0    response.forEach{        if(it.startsWith("4")){            clientErrors++        }else if(it.startsWith("5")){            serverErrors++        }    }    println("$clientErrors client errors,$serverErrors server errors")}//filter 可以删除你不想要的元素,你不能改变里面的 元素fun testCollectionFilter(){    val list = listOf(1,2,3,4)    list.filter { it % 2 == 0 }     val people = listOf(Person("Alice",29),Person("Bob",31))    people.filter { it.age > 30 }}//map 可以改变集合里面的 元素的 值 产生一个新的集合fun testMapFun(){  val list = listOf(1,2,3,4)    list.map { it*it }    val people = listOf(Person("Alice",29),Person("Bob",31))    people.map { it.name }    //找出最大年龄的人    people.filter { it.age == people.maxBy(Person::age)?.age }    //这句话 it.age == people.maxBy(Person::age)?.age 每次循环的 时候都会执行它    //换成下面的 写法    val maxAge = people.maxBy(Person::age)?.age    people.filter { it.age == maxAge }    val numbers = mapOf(0 to "zero", 1 to "one")    println(numbers.mapValues { it.value.toUpperCase() })}val people = listOf(Person("Alice",29),Person("Bob",31),Person("linda",31))//检查所有元素是否满足条件fun testAll(){    val people = listOf(Person("Alice",29),Person("Bob",31))    val canBeInClub27 = { p: Person -> p.age <= 27}    people.all(canBeInClub27)}//检查是否有一个元素满足条件fun testAnyFun(){    val canBeInClub27 = { p: Person -> p.age <= 27}    people.any(canBeInClub27)    //另一种写法    !people.all(canBeInClub27)}//满足某个条件的集合的个数fun testCountFun(){    val canBeInClub27 = { p: Person -> p.age <= 27}    people.count(canBeInClub27)}//满足某个条件第一个元素fun testFind(){    val canBeInClub27 = { p: Person -> p.age <= 27}    people.find(canBeInClub27)//这两个函数等价的    people.firstOrNull(canBeInClub27)}//将一个列表结合转为mapfun testListToMap(){ println(people.groupBy { it.age })    //根据年龄分组    //key 是age value List<Person>    //将字符串集合 根据第一个字母 分组    val list = listOf("a","ab","b")    println(list.groupBy (String::first ))}class Book(val title: String, val authors: List<String>)val books = listOf(Book("Thursday Next", listOf("Jasper Fforge")),Book("Mort",listOf("Terry Partchett")),Book("Good Omens", listOf("Terry Partchett")))fun testFlatMap(){//将books 里的所有作者单独提出来的集合 toSet会去重    println(books.flatMap { it.authors }.toSet())//不去重 你可以使用 flatten}//fun testSequences(){    people.map(Person::name).filter{ it.startsWith("A")}//这个函数会产生两个临时变量集合 一个是filter 一个是map 这个就会产生效率问题    //下面这种情况可以避免    people.asSequence().map(Person::name).filter { it.startsWith("A") }.toList()    val naturalNumbers = generateSequence (0){ it+1  }    val numbersTo100 = naturalNumbers            .takeWhile {  it <= 100 }    println(numbersTo100.sum())}
原创粉丝点击