lambda的几种形式
Runnable a = () -> System.out.println("hello world");
ActionListener b = event -> System.out.println("button action");
Runnable c = () -> {
System.out.println("hello");
System.out.println("world");
}
BinaryOperator<Long> d = (x,y) -> x+y;
BinaryOperator<Long> e = (long x , long y) -> x + y;
a 表达式 不包含参数 ,使用()表示没有参数,该表达式实现了Runnable接口,接口只有一个方法,返回void;
b 表达式 包含一个参数 可省略 ();
c 表达式 使用代码块表达;
d 表达式 d的类型是BinaryOperator 而不是x+y的和,等号右边是一个函数,参数类型由编译器推断;
e 表达式 指定参数类型;
lambda 表达式中的引用的(局部变量)是值而不是变量或既成事实上的final变量
String a = "aa"; Button b = new Button(); b.addActionListener(event -> System.out.print("aa"+a));
串a 没有改变 所以相当于final的 是即成事实上的final
但是如果改变a 所指向的对象;
String a = "aa"; a = "bb"; Button b = new Button(); b.addActionListener(event -> System.out.print("aa"+a));
编译器就会报错:variable used in lambda expression should be final or effiectively final.
所以lambda表达式也叫闭包(点击直接进入百度百科)。未赋值的变量与周边环境隔离起来,进而被绑定到一个特定的值。
函数接口:具有单个抽象方法的接口,用来表达lambda表达式的类型
接口 | 参数 | 返回类型 | 示例 |
---|---|---|---|
Predicate<T> | T | boolean | 今天写博客了么 |
Consumer<T> | T | void | 打印一段话 |
Funcation<T,R> | T | R | 枚举的valueof Map的get |
Supplier<T> | Null | T | 工厂方法 |
UnaryOperator<T> | T | T | 逻辑非??? |
BinaryOperator<T> | (T,T) | T | 加减乘除 |
类型推断
Predicate<Integer> dd = x -> x>5; if(dd.test(1)){}
上表达式可判断
BinaryOperator a = (x,y) -> x+y;
上表达式无范性 , 无法判断
内部迭代
java.util.List<Integer> aa = new ArrayList<>(); aa.add(55); aa.add(44); aa.add(1); aa.add(2); long count = aa.stream() .filter(i -> i>5) .count(); System.out.print(count);
找出List中大于5的数;
stream 该方法返回内部迭代的响应接口Stream
filter 过滤 指保留通过某项测试的对象 该函数返回 true 或 false
count 计算给定Stream里包含多少个对象。