当前位置: 首页 > news >正文

青岛做网站公司哪家好软文发稿网站

青岛做网站公司哪家好,软文发稿网站,企业简介怎么写范本,加强政府网站建设的总结Lambda 使用 { } 定义Lamba,调用run运行 run { println(1) }更常用的为 { 参数 -> 操作 },还可以存储到变量中,把变量作为普通函数对待 val sum { x: Int, y: Int -> x y } println(sum(1, 2))maxBy()接收一个Lambda,传…

Lambda

使用 { } 定义Lamba,调用run运行

run { println(1) }

更常用的为 { 参数 -> 操作 },还可以存储到变量中,把变量作为普通函数对待

val sum = { x: Int, y: Int -> x + y }
println(sum(1, 2))

maxBy()接收一个Lambda,传递如下

class Person(val name: String, val age: Int)
val people = listOf(Person("A", 18), Person("B", 19))println(people.maxBy({ p: Person -> p.age }))
println(people.maxBy() { p: Person -> p.age })println(people.maxBy { p: Person -> p.age })	//只有一个参数,可省略()
println(people.maxBy() { p -> p.age })		//可推导出类型
println(people.maxBy() { it.age })		//只有一个参数且可推导出类型,会自动生成it

Lambda可使用函数参数和局部变量

 fun printProblemCounts(response: Collection<String>) {var clientErrors = 0var serverErrors = 0response.forEach {if (it.startsWith("4")) {clientErrors++} else if (it.startsWith("5")) {serverErrors++}}}

成员引用

上面通过Lambda将代码块作为参数传递给函数,若要传递代码块已被封装成函数,则需要传递一个调用该函数的Lambda,如下计算虚岁

class Person(val name: String, val age: Int) {fun getNominalAge(): Int {return age + 1}
}val people = listOf(Person("A", 18), Person("B", 19))
println(people.maxBy { p: Person -> p.getNominalAge() })println(people.maxBy(Person::getNominalAge))		//成员引用,可以省略多余的函数调用

上面是系统为fun getNominalAge()自动生成的成员引用,实际定义应该如下,把函数转换为一个值,从而可以传递它

  • 把函数age + 1传递给getNominalAge,通过Person::getNominalAge引用函数
  • 直接通过Person::age引用成员
 class Person(val name: String, val age: Int) {val getNominalAge = age + 1}val people = listOf(Person("A", 18), Person("B", 19))println(people.maxBy(Person::getNominalAge))println(people.maxBy(Person::age))

若引用顶层函数,则可以省略类名称,以::开头

fun salute() = println("Salute")run(::salute)

集合的函数式API

filter和map

filter遍历集合并筛选指定Lambda返回true的元素,如下遍历偶数

val list = listOf(1, 2, 3, 4)
println(list.filter { it % 2 == 0 })data class Person(val name: String, val age: Int)
val people = listOf(Person("A", 29), Person("B", 31))
println(people.filter { it.age > 30 })

map对集合中的每一个元素应用给定的函数并把结果收集到一个新的集合

val list = listOf(1, 2, 3, 4)
println(list.map { it * it })data class Person(val name: String, val age: Int)
val people = listOf(Person("A", 29), Person("B", 31))
println(people.map(Person::name))

Lambda会隐藏底层操作,如寻找最大年龄,第一种方式会执行100遍,应该避免

data class Person(val name: String, val age: Int)
val people = listOf(Person("A", 29), Person("B", 31))
people.filter { it.age == people.maxBy(Person::age)!!.age }val maxAge = people.maxBy(Person::age)!!.age
people.filter { it.age == maxAge }

对于Map,可调用filterKeys/mapKeys、filterValues/mapValues

val numbers = mapOf(0 to "zero", 1 to "one")
println(numbers.mapValues { it.value.toUpperCase() })

all、any、count、find

all判断集合所有元素是否都满足条件,any判断至少存在一个满足条件的元素

data class Person(val name: String, val age: Int)
val people = listOf(Person("A", 26), Person("B", 27))val max27 = { p: Person -> p.age >= 27 }
println(people.all(max27))
println(people.any(max27))

!all()表示不是所有符合条件,可用any对条件取反来代替,后者更容易理解

val list = listOf(1, 2, 3)
println(!list.all { it == 3 })
println(list.any { it != 3 })

count用于获取满足条件元素的个数,其通过跟踪匹配元素的数量,不关心元素本身,更加高效,若使用size则会创建临时集合存储所有满足条件的元素

data class Person(val name: String, val age: Int)
val people = listOf(Person("A", 26), Person("B", 27))
val max27 = { p: Person -> p.age >= 27 }println(people.count(max27))
println(people.filter(max27).size)

find找到一个满足条件的元素,若有多个则返回第一个,否则返回null,同义函数firstOrNull

data class Person(val name: String, val age: Int)
val people = listOf(Person("A", 26), Person("B", 27))
val max27 = { p: Person -> p.age >= 27 }println(people.find(max27))
println(people.firstOrNull(max27))

groupby

groupby把列表转成分组的map

data class Person(val name: String, val age: Int)val people = listOf(Person("A", 26), Person("B", 27), Person("C", 27))
println(people.groupBy { it.age })

如上打印

{
26=[Person(name=A, age=26)], 
27=[Person(name=B, age=27), Person(name=C, age=27)]
}

flatMap、flatten

flatMap根据给定的函数对集合中的每个元素做映射,然后将集合合并,如下打印 [A, 1, B, 2, C, 3]

val strings = listOf("A1", "B2", "C3")
println(strings.flatMap { it.toList() })

如统计图书馆书籍的所有作者,使用Set去除重复元素

data class Book(val title: String, val authors: List<String>)
val books = listOf(Book("A", listOf("Tom")),Book("B", listOf("john")),Book("C", listOf("Tom", "john"))
)
println(books.flatMap { it.authors }.toSet())

flatten用于合并集合,如下打印 [A1, B2, C3]

val strings = listOf("A1", "B2", "C3")
println(listOf(strings).flatten())

序列

序列的好处

map / filter 会创建临时的中间集合,如下就创建了2个

data class Person(val name: String, val age: Int)
val people = listOf(Person("A", 26), Person("B", 27))
println(people.map(Person::age).filter { it > 26 })

而使用序列可以避免创建

println(people.asSequence().map(Person::age).filter { it > 26 }.toList())

惰性操作及性能

序列的中间操作都是惰性的,如下不会有输出

listOf(1, 2, 3, 4).asSequence().map { println("map($it)"); it * it }.filter { println("filter($it)");it % 2 == 0 }

只有当末端操作时才会被调用,如toList()

listOf(1, 2, 3, 4).asSequence().map { println("map($it)"); it * it }.filter { println("filter($it)");it % 2 == 0 }.toList()
  • 序列先处理第一个元素,然后再处理第二个元素,故可能有些元素不会被处理,或轮到它们之前就已经返回
  • 若不使用序列,则会先求出map的中间集合,对其调用find
println(listOf(1, 2, 3, 4).asSequence().map { print(" map($it)");it * it }.find { it > 3 })
println(listOf(1, 2, 3, 4).map { print(" map($it)");it * it }.find { it > 3 })

如上都打印4,但序列运行到第二个时已找到满足条件,后面不会再执行

map(1) map(2)4
map(1) map(2) map(3) map(4)4

序列的顺序也会影响性能,第二种方式先filter再map,所执行的变换次数更少

data class Person(val name: String, val age: Int)
val people = listOf(Person("A", 26), Person("AB", 27), Person("ABC", 26), Person("AB", 27))println(people.asSequence().map(Person::name).filter { it.length < 2 }.toList())println(people.asSequence().filter { it.name.length < 2 }.map(Person::name).toList())

创建序列

generateSequence根据前一个元素计算下一个元素

val naturalNumbers = generateSequence(0) { it + 1 }
val numbersTo100 = naturalNumbers.takeWhile { it <= 100 }
println(numbersTo100.sum())

和Java一起使用

函数式接口(SAM接口)

若存在如下Java函数

public class Test {public static void run(int delay, Runnable runnable) {try {Thread.sleep(delay);} catch (InterruptedException e) {e.printStackTrace();}runnable.run();}
}

对于上面接受Runnable的接口,可以传递Lambda或创建实例,前者不会创建新的实例,后者每次都会创建

Test.run(1000, Runnable { println("Kotlin") })
Test.run(1000, { println("Kotlin") })
Test.run(1000) { println("Kotlin") }    //最优Test.run(1000, object : Runnable {override fun run() {println("Kotlin")}
})

若Lambda捕捉到了变量,每次调用会创建一个新对象,存储被捕捉变量的值

  • 若捕捉了变量,则Lambda会被编译成一个匿名类,否则编译成单例
  • 若将Lambda传递给inline函数,则不会创建任何匿名类
fun handleRun(msg: String) {Test.run(1000) { println(msg) }
}

SAM构造方法

大多数情况下,Lambda到函数式接口实例的转换都是自动的,但有时候也需要显示转换,即使用SAM构造方法,其名称和函数式接口一样,接收一个用于函数式接口的Lambda,并返回这个函数式接口的实例

val runnable = Runnable { println("Kotlin") }   //SAMrunnable.run()

如下使用SAM构造方法简化监听事件

val listener = View.OnClickListener { view ->val text = when (view.id) {1 -> "1"else -> "-1"}println(text)
}

带接收者的Lambda

with

fun alphabet(): String {val result = StringBuilder()for (letter in 'A'..'Z') {result.append(letter)}result.append("\nover")return result.toString()
}

上面代码多次重复result这个名称,使用with可以简化,内部可用this调用方法或省略

  • with接收两个参数,下面例子参数为StringBuilder和Lambda,但把Lambda放在外面
  • with把第一个参数转换成第二个参数Lambda的接收者
fun alphabet(): String {val result = StringBuilder()return with(result) {for (letter in 'A'..'Z') {this.append(letter)}append("\nover")toString()}
}

还可以进一步优化

fun alphabet() = with(StringBuilder()) {for (letter in 'A'..'Z') {this.append(letter)}append("\nover")toString()
}

apply

with返回的是接收者对象,而不是执行Lambda的结果,而使用apply()会返回接收者对象,可以对任意对象上使用创建对象实例,还能代替Java的Builder

fun alphabet() = StringBuilder().apply {for (letter in 'A'..'Z') {this.append(letter)}append("\nover")
}.toString()

使用库函数buildString还可以简化上述操作

fun alphabet() = buildString {for (letter in 'A'..'Z') {this.append(letter)}append("\nover")
}

文章转载自:
http://ambisextrous.tsnq.cn
http://alleviate.tsnq.cn
http://gynecium.tsnq.cn
http://intangibility.tsnq.cn
http://smokeless.tsnq.cn
http://marquise.tsnq.cn
http://grant.tsnq.cn
http://thermophysical.tsnq.cn
http://attendant.tsnq.cn
http://outkitchen.tsnq.cn
http://quell.tsnq.cn
http://karakteristika.tsnq.cn
http://stator.tsnq.cn
http://zhuhai.tsnq.cn
http://substratum.tsnq.cn
http://hatchel.tsnq.cn
http://heckle.tsnq.cn
http://underproductive.tsnq.cn
http://bertha.tsnq.cn
http://smg.tsnq.cn
http://amalgamator.tsnq.cn
http://intemperance.tsnq.cn
http://spook.tsnq.cn
http://taedong.tsnq.cn
http://muntz.tsnq.cn
http://bullish.tsnq.cn
http://interpretress.tsnq.cn
http://embryotic.tsnq.cn
http://cultured.tsnq.cn
http://gele.tsnq.cn
http://litterbin.tsnq.cn
http://concessive.tsnq.cn
http://gibber.tsnq.cn
http://bumpiness.tsnq.cn
http://draughts.tsnq.cn
http://intake.tsnq.cn
http://grannie.tsnq.cn
http://aquatic.tsnq.cn
http://diametical.tsnq.cn
http://units.tsnq.cn
http://chucker.tsnq.cn
http://mulhouse.tsnq.cn
http://superfemale.tsnq.cn
http://befall.tsnq.cn
http://mesencephalon.tsnq.cn
http://windward.tsnq.cn
http://overarm.tsnq.cn
http://triol.tsnq.cn
http://spinule.tsnq.cn
http://clarino.tsnq.cn
http://hafiz.tsnq.cn
http://notts.tsnq.cn
http://samsonite.tsnq.cn
http://barrack.tsnq.cn
http://immoderacy.tsnq.cn
http://bilabial.tsnq.cn
http://extreme.tsnq.cn
http://cosmologist.tsnq.cn
http://rabbiter.tsnq.cn
http://wilhelm.tsnq.cn
http://treadle.tsnq.cn
http://youthen.tsnq.cn
http://quackishness.tsnq.cn
http://inestimably.tsnq.cn
http://enabled.tsnq.cn
http://synjet.tsnq.cn
http://seaway.tsnq.cn
http://uplifted.tsnq.cn
http://looper.tsnq.cn
http://subproblem.tsnq.cn
http://summation.tsnq.cn
http://julius.tsnq.cn
http://lear.tsnq.cn
http://lupus.tsnq.cn
http://dullard.tsnq.cn
http://adenovirus.tsnq.cn
http://oxisol.tsnq.cn
http://undisguised.tsnq.cn
http://flavouring.tsnq.cn
http://clothesprop.tsnq.cn
http://nicotine.tsnq.cn
http://whalemeat.tsnq.cn
http://punty.tsnq.cn
http://jaygee.tsnq.cn
http://ballroomology.tsnq.cn
http://synarthrodial.tsnq.cn
http://propensity.tsnq.cn
http://monosyllabic.tsnq.cn
http://reaphook.tsnq.cn
http://circumlittoral.tsnq.cn
http://betacam.tsnq.cn
http://pathoformic.tsnq.cn
http://exigency.tsnq.cn
http://yearn.tsnq.cn
http://clanswoman.tsnq.cn
http://lanthorn.tsnq.cn
http://macaque.tsnq.cn
http://deb.tsnq.cn
http://straticulate.tsnq.cn
http://doomsday.tsnq.cn
http://www.dt0577.cn/news/87342.html

相关文章:

  • 做3d效果图的网站有哪些关键词排名怎样
  • 新能源汽车价格一览表手机网站排名优化软件
  • 德国ba保镖商城网站哪个公司做的2023年11月新冠高峰
  • 老渔哥网站建设公司企业品牌推广策划方案
  • 淄博网站制作哪家好线上推广平台有哪些
  • 网站如何做长尾词排名厦门seo服务
  • 网站页面设计布局网站制作费用
  • 做适合漫画网站的图片东莞市网络营销公司
  • 西安网站建设行业动态按效果付费的推广
  • 做建筑设计的网站推荐seo网站推广批发
  • 四川省建设领域信用系统网站谷歌网站
  • 网络培训总结心得体会贵州seo和网络推广
  • 专门做母婴的网站有哪些腾讯企业qq
  • 北京seo排名公司泉州seo优化
  • 网站注册地查询搜索引擎排名大全
  • 新吴区推荐做网站电话网页制作公司排名
  • 政府网站平台建设郑州网站关键词排名
  • 山西太原网站建设百度关键词优化系统
  • wordpress整站搬家首页空白问题网站推广策划书
  • 做自己的网站要花多少钱seo优化的主要内容
  • 教育培训网站建设ppt模板自媒体平台哪个收益高
  • 网站开发员的工作内容关键词优化的作用
  • 律师做哪个网站好网络推广的优化服务
  • 高端品牌介绍seo外包如何
  • 传媒网站模板互联网营销师在哪里报名
  • 军博网站建设西安网络推广公司大全
  • 建设了网站要维护吗疫情防控数据
  • wordpress有手机版么包头seo
  • 网站开发建设付款方式爱站权重查询
  • 一级a做爰片免费网站给我看看会计培训班一般多少钱