根据使用场景不同,Lambda表达式的常见使用方法通常有三种写法。
import org.junit.Test;
/**
* Lambda Test
* Created by Joker on 2017/8/8.
*/
public class LambdaD {
static class Math {
private static Object execute(Integer... args) {
Integer sum = 0;
for (Integer arg : args) {
sum += arg;
}
return sum;
}
}
interface Executor {
Object execute(Integer... args);
}
private Object runExecute(Executor executor, Integer... args) {
return executor.execute(args);
}
@Test
public void test() {
System.out.println(runExecute(Math::execute, 1, 2, 3));
System.out.println(runExecute(args -> Math.execute(args), 1, 2, 3));
System.out.println(runExecute((Integer... args)-> {return args[0]+args[1]+args[2];}, 1, 2, 3));
}
}
以下简单的仿照List forEach方法:
import com.springtest.colligate.Add;
import org.junit.Test;
import java.util.*;
import java.util.function.Consumer;
/**
* Lambda Test
* Created by Joker on 2017/8/8.
*/
public class LambdaE {
class CustomerList<T>{
List<T> listData = new ArrayList<>();
void add(T t) {
listData.add(t);
}
void forEach(Executor<? super T> action) {
Objects.requireNonNull(action);
for (T t : listData) {
action.runAction(t);
}
}
}
interface Executor<T> {
void runAction(T t);
}
@Test
public void test(){
CustomerList<String> aaa = new CustomerList<String>();
aaa.add("WuYiFan");
aaa.add("TFBoys");
aaa.add("Angelababy");
aaa.forEach(a->{System.out.println(a);});
}
}
总结:当某个类在需要接口类型构造方法时,我们可以以Lambda的形式申明该接口的实例。其本质是对传入的对象做怎样的操作。