Java Lambda
时间:2018-07-02 10:39:33
收藏:0
阅读:219
- lambda从Java8开始
基础语法
expression = (variable) -> action
- variable: 这是一个变量,一个占位符。像x,y,z,可以是多个变量;
- action: 这里我称它为action, 这是我们实现的代码逻辑部分,它可以是一行代码也可以是一个代码片段。
函数式接口
- 注解@FunctionalInterface标识一个接口为函数式接口,被标识的接口只能有一个抽象方法,否则会报错
- 不标识@FunctionalInterface的接口,但事实上也是函数式接口的,依然可以使用lambda表达式
- JDK中的函数式接口位置:
java.util.function
四大核心函数式接口:

消费型接口示例
public static void donation(Integer money, Consumer<Integer> consumer){
consumer.accept(money);
}
public static void main(String[] args) {
donation(1000, money -> System.out.println("好心的麦乐迪为Blade捐赠了"+money+"元")) ;
}
供给型接口示例
public static List<Integer> supply(Integer num, Supplier<Integer> supplier){
List<Integer> resultList = new ArrayList<Integer>() ;
for(int x=0;x<num;x++)
resultList.add(supplier.get());
return resultList ;
}
public static void main(String[] args) {
List<Integer> list = supply(10,() -> (int)(Math.random()*100));
list.forEach(System.out::println);
}
函数型接口示例
public static Integer convert(String str, Function<String, Integer> function) {
return function.apply(str);
}
public static void main(String[] args) {
Integer value = convert("28", x -> Integer.parseInt(x));
}
断言型接口示例
public static List<String> filter(List<String> fruit, Predicate<String> predicate){
List<String> f = new ArrayList<>();
for (String s : fruit) {
if(predicate.test(s)){
f.add(s);
}
}
return f;
}
public static void main(String[] args) {
List<String> fruit = Arrays.asList("香蕉", "哈密瓜", "榴莲", "火龙果", "水蜜桃");
List<String> newFruit = filter(fruit, (f) -> f.length() == 2);
System.out.println(newFruit);
}
自定义函数式接口
- 实现简单加法
public class Test2 {
/*
一个接口,如果只有一个显式声明的抽象方法,
那么它就是一个函数接口。
一般用@FunctionalInterface标注出来(也可以不标)
*/
interface Inteface1 {
// 可以不用abstract修饰
public abstract void test(int x, int y);
// public void test1();//会报错,不能有两个方法,尽管没有使用abstract修饰
public boolean equals(Object o);// equals属于Object的方法,所以不会报错
}
public static void main(String args[]) {
Inteface1 f1 = (x, y) -> {
System.out.println(x + y);
};
f1.test(3, 4);
Inteface1 f2 = (int x, int y) -> {
System.out.println("Hello Lambda!\t the result is " + (x + y));
};
f2.test(3, 4);
}
}
lambda 表达式和闭包
- 类似于在匿名类内部引用函数局部变量,必须将其声明为final
public static Supplier<Integer> testClosure() {
int i = 1;
// i++; // 会报错
return () -> {
return i;
};
}
参考资料
- 跟上 Java 8 – 了解 lambda
- 深入理解Java 8 Lambda(语言篇——lambda,方法引用,目标类型和默认方法)
- 用java 8里面的lambda表达式写一个简单加法运算
- lambda 表达式和闭包
原文:https://www.cnblogs.com/huangwenjie/p/9252116.html
评论(0)