特点
- 函数传递
- 函数编程
- 闭包
Java 中的 Lambda 表达式通常使用 (argument) -> (body) 语法书写,例如:
(arg1, arg2…) -> { body }
(type1 arg1, type2 arg2…) -> { body }
以下是一些 Lambda 表达式的例子:1
2
3
4
5
6
7
8
9(int a, int b) -> { return a + b; }
() -> System.out.println("Hello World");
(String s) -> { System.out.println(s); }
() -> 42
() -> { return 3.1415 };
每个 Lambda 表达式都能隐式地赋值给函数式接口,例如,我们可以通过 Lambda 表达式创建 Runnable 接口的引用。1
Runnable r = () -> System.out.println("hello world");
当不指明函数式接口时,编译器会自动解释这种转化:1
2
3new Thread(
() -> System.out.println("hello world")
).start();
@FunctionalInterface
函数式接口只能有一个抽象方法,如果你尝试添加第二个抽象方法,将抛出编译时错误1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28//定义一个函数式接口
### @FunctionalInterface
public interface WorkerInterface {
public void doSomeWork();
}
public class WorkerInterfaceTest {
public static void execute(WorkerInterface worker) {
worker.doSomeWork();
}
public static void main(String [] args) {
//invoke doSomeWork using Annonymous class
execute(new WorkerInterface() {
public void doSomeWork() {
System.out.println("Worker invoked using Anonymous class");
}
});
//invoke doSomeWork using Lambda expression
execute( () -> System.out.println("Worker invoked using Lambda expression") );
}
}
用法区别
1 | //Old way: |
findAny
1 | Optional<A> optional = list().stream().filter(e -> |
collect
1 | tagList = list.parallelStream().filter(e ->e.getType() == tag.getType() |
map
1 | List<String> list = tagList.stream().map(Tag::getValue).collect(Collectors.toList()); |
limit
1 | Stream.iterate(0, i -> i + 1).limit(tagList.size()).forEach( |
forEach
1 | tagList().forEach(e -> { |
comparing
1 | list.sort(Comparator.comparing(e -> e.getPriority())); |
parallelStream
1 | public Ele getEle() { |
of
1 | Stream.of("张三","李四","王二","张四五") |
removeIf 移除元素
1 | List<String> str1 = new ArrayList<String>(); |