1、lambda表达式的书写
(1)lambda表达式:在java中Lambda表达式是对象,他们必须依赖于一类特别的对象类型函数式接口
@FunctionalInterface
interface MyInterface1{
void myMethod1();
}
@FunctionalInterface
interface MyInterface2{
void myMethod2();
}
public class Test1 {
public static void main(String[] args) {
MyInterface1 interface1=()->{};
System.out.println(interface1.getClass().getInterfaces()[0]);
MyInterface2 interface2=()->{};
System.out.println(interface2.getClass().getInterfaces()[0]);
}
}
表达式的书写一定要根据上下文信息(两个函数式接口):
例如:
interface MyInterface2{
void myMethod2();
}
接口是无参数的,那么lambda表达式的小括号代表参数内容(这里为空),{ },代表的是接口中的内容(这里面的函数式接口不接收参数,不返回值,():方法的参数,{}:方法的实现),函数式接口是直接找的抽象方法。
2、Runable接口
(1)它是一个函数式接口,因为该接口只有一个抽象方法:
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
(2)创建一个线程:
普通方式:
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
lambda表达式:
new Thread(()->System.out.println("ni hao")).start();
3、应用
(1) 小写转换为大写:
public static void main(String[] args) {
List<String> list= Arrays.asList("jia","you");
list.forEach(item->System.out.println(item.toUpperCase()));
}
JIA
YOU
(2)小写转大写后,在存储到一个新的集合中:
public static void main(String[] args) {
List<String> list= Arrays.asList("jia","you");
List<String> list1=new ArrayList<>();
list.forEach(item->list1.add(item.toUpperCase()));
list1.forEach(item->System.out.println(item));
}
转化为流后处理:
public static void main(String[] args) {
List<String> list= Arrays.asList("jia","you");
list.stream().map(item->item.toUpperCase()).forEach(item->System.out.println(item));
}
方法的引用方式实现:
public static void main(String[] args) {
List<String> list= Arrays.asList("jia","you");
list.stream().map(String::toUpperCase).forEach(item->System.out.println(item));
}