Kotlin函数式API
1.maxBy
val list = listOf("Apple","Banana", "Orange","pear","Grape","Watermelon")
val maxLengthFruit = list.maxBy {it.length}
println(maxLengthFruit)
2.map
集合中zhi的map函数是最常用的一种函数式API,它用于将集合中的每个元素都映射成另一个值,映射规则在Lambda表达式中指定,最终生产一个新的集合。
val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape", "Watermelon")
val newList = list.map{it.toUpperCase()}
printlin(newList)
3.filter(过滤)
val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape", "Watermelon")
val newList = list.filter {it.length <= 5}.map {it.toUpperCase()}
println(newList)
4.any and all
any用于判断是否存在某个元素满足指定条件,all用于判断是否所有元素均满足指定条件;返回值均为Boolean类型
val list = listOf("Apple", "Banana", "Orange", "Grape", "Pear", "Watermelon")
println(list.any{it.length <= 5})
println(list.all{it.length <= 5})
Java函数式API
如果我们想用Kotlin代码调用一个Java方法,且该方法接受一个单抽象方法接口参数(单抽象方法接口是指接口中只有一个待实现方法),便可以使用函数式API
//Java原生API中最常见的单抽象方法接口——Runnable接口
public interface Runnable {
void fun();
}
//Java中Runnbale接口与线程的结合实现
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("The thread is running.");
}
}).start();
/*注:这里使用匿名类的写法,
传递给Thread构造方法的便是一个Runnable接口的匿名类实例,
最后调用start方法启动线程;
匿名类是一种一次性使用,没有显示名称的局部类,
通常用于实现接口和继承类*/
//Kotlin中Runnbale接口与线程的结合实现
Thread(object : Runnable {
override fun run() {
println("The thread is running.")
}
}).start()
//精简后:
Thread(Runnable {
println("The thread is running.")
}).start()
//进一步精简:
Thread {
println("The thread is running.")
}.start()