Java支持Lambda 表达式始于Java 8,它的出现简化了函数式接口匿名内部类的语法,其表达式语法如下:([参数1], [参数2], [参数3],… [参数n])->{代码块}
匿名内部类:
@FunctionalInterface
interface IComputer {
void add(int a, int b);
}
public class Test {
public static void main(String[] args) {
IComputer computer = new IComputer() {
@Override
public void add(int a, int b) {
System.out.println(a + b);
}
};
computer.add(1, 1);
}
}
Lambda 表达式:
@FunctionalInterface
interface IComputer {
void add(int a, int b);
}
public class Test {
public static void main(String[] args) {
IComputer computer = (int a, int b)-> {
System.out.println(a + b);
};
computer.add(1, 1);
}
}
如果方法没有返回值且只有一行代码,则Lambda表达式语法可以是这种形式:([参数1], [参数2], [参数3],… [参数n])->单行语句,如下例:
匿名内部类:
@FunctionalInterface
interface IMammal {
void move(String name);
}
public class Test {
public static void main(String[] args) {
IMammal whale = (name) -> {
System.out.println(name+"正在移动......");
};
whale.move("鲸鱼");
}
}
Lambda 表达式:
@FunctionalInterface
interface IMammal {
void move(String name);
}
public class Test {
public static void main(String[] args) {
IMammal whale = (name) -> System.out.println(name+"正在移动......");
whale.move("鲸鱼");
}
}
如果方法有返回值且只有一行代码,则Lambda表达式语法可以是这种形式:([参数1], [参数2], [参数3],… [参数n])->表达式,如下例:
匿名内部类:
@FunctionalInterface
interface IComputer {
int add(int a, int b);
}
public class Test {
public static void main(String[] args) {
IComputer computer = (a, b) -> {
return a+b;
};
int result = computer.add(1,2);
System.out.println(result);
}
}
Lambda 表达式:
@FunctionalInterface
interface IComputer {
int add(int a, int b);
}
public class Test {
public static void main(String[] args) {
IComputer computer = (a, b) -> a+b;
int result = computer.add(1,2);
System.out.println(result);
}
}