Java8新特性
1 Lambda表达式
1.1 使用Lambda表达式实现函数式接口1
【案例1】函数是接口 MyInterOne
//函数式接口(接口中只有一个抽象方法)
@FunctionalInterface
public interface MyInterOne {
public abstract void methodOne();
}
【案例2】定义MyInterOneImpl类实现接口MyInterOne
public class MyInterOneImpl implements MyInterOne {
@Override
public void methodOne() {
System.out.println("in MyInterOneImpl methodOne()~~~~~~~~~~~~~~~");
}
}
【案例3】
public class TestOne {
public static void main(String[] args) {
MyInterOne myInterOne = new MyInterOneImpl();
//0.创建对象调用方法
myInterOne.methodOne();
//1.内部类实现接口
MyInterOne myInterTwo = new MyInterOne() {
@Override
public void methodOne() {
System.out.println("in innerClass methodOne()~~~~~~~~~~~~~~~~");
}
};
myInterTwo.methodOne();
//2.lambda表达式只能用于实现函数式接口
MyInterOne myInterThree = () -> {System.out.println("in lambda methodOne()~~~~~~~~~~~~~~~~~~~~~~~");};
myInterThree.methodOne();
}
}
1.2 使用Lambda表达式实现函数式接口2
【案例1】多个接口,方法分别无参、有一个参数、多个参数
// 函数式接口(接口中只有一个抽象方法)
@FunctionalInterface
public interface MyInterOne {
public abstract void methodOne();
}
@FunctionalInterface
interface MyInterTwo{
public abstract void methodTwo(String s);
}
@FunctionalInterface
interface MyInterThree{
public abstract void methodThree(String s,int i);
}
【案例2】
public class TestTwo {
public static void main(String[] args) {
// 函数式实现接口的几种方式
MyInterOne myInterOne = new MyInterOne() {
@Override
public void methodOne() {
System.out.println("in innerClass methodOne~~~~~~~~~~~~~~~~~");
}
};
myInterOne.methodOne();
// lambda表达式实现
//1.接口中的方法 无参
//1.1 如果方法的实现体有多行代码,则必须保留方法大括号
MyInterOne myInterOne1 = () -> {
System.out.println("in myInterTwo methodOne~~~~~~~~~~~~~~~~~~~~~");
};
myInterOne.methodOne();
//1.2 如果方法的实现只有一行代码,则可以省略大括号
MyInterOne myInterOne2 = () -> System.out.println("in myInterTwo methodOne~~~~~~~~~~~~~~~~~");
myInterOne2.methodOne();
//2.单个形参情况下
//2.1 形参给出类型和形参名
MyInterTwo myInterTwo = (String s) -> System.out.println(s);
myInterTwo.methodTwo("hello world1");
//2.2 形参可以不给类型,只给形参名
MyInterTwo myInterTwo1 = (s) -> System.out.println(s);
myInterTwo1.methodTwo("hello world2");
//2.3 如果形参只有一个参数,则可以省略小括号
MyInterTwo myInterTwo2 = s -> System.out.println(s);
myInterTwo2.methodTwo("hello world3");
// 3.多个形参情况下
// 3.1给出每个参数的参数类型和参数名
MyInterThree myInterThree = (String s,int i) -> System.out.println("s="+s+",i="+i);
myInterThree.methodThree("hello",101);
// 3.2给出每个参数形参名,省略形参类型
MyInterThree myInterThree1 = (s,i) -> System.out.println("s="+s+",i="+i);
myInterThree1.methodThree("ok",202);
}
}
1.3 使用Lambda表达式实现函数式接口3