Java支持Lambda 表达式始于Java 8,它的出现简化了函数式接口匿名内部类的语法
匿名内部类:
@FunctionalInterface
interface IArrayUtil{
void iterate(Object [] array);
}
public class Test {
public static void main(String args[]){
IArrayUtil arrayUtil = new IArrayUtil() {
@Override
public void iterate(Object[] array) {
for (Object obj : array) {
System.out.println(obj);
}
}
};
arrayUtil.iterate(new String[] {"小张","小王"});
}
}
Lambda 表达式:
@FunctionalInterface
interface IArrayUtil {
void iterate(Object[] array);
}
public class Test {
public static void main(String args[]) {
IArrayUtil arrayUtil = (Object[] array) -> {
for (Object obj : array) {
System.out.println(obj);
}
};
arrayUtil.iterate(new String[] { "小张", "小王"});
}
}
匿名内部类:
import java.util.Date;
public class Test {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(new Date());
}
};
new Thread(runnable).start();
}
}
Lambda 表达式:
import java.util.Date;
public class Test {
public static void main(String[] args) {
new Thread(() -> {
System.out.println(new Date());
}).start();
}
}
如果方法没有返回值且只有一行代码,则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 表达式:
@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 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);
}
}