Java Lambda用法

特点

  • 函数传递
  • 函数编程
  • 闭包

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
3
new 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() {
@Override
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
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//Old way:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
for(Integer n: list) {
System.out.println(n);
}

//New way:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
list.forEach(n -> System.out.println(n));


//or we can use :: double colon operator in Java 8
list.forEach(System.out::println);

public class Main {

public static void main(String [] a) {

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

System.out.println("Print all numbers:");
evaluate(list, (n)->true);

System.out.println("Print no numbers:");
evaluate(list, (n)->false);

System.out.println("Print even numbers:");
evaluate(list, (n)-> n%2 == 0 );

System.out.println("Print odd numbers:");
evaluate(list, (n)-> n%2 == 1 );

System.out.println("Print numbers greater than 5:");
evaluate(list, (n)-> n > 5 );

}

public static void evaluate(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list) {
if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}

}

//Old way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
for(Integer n : list) {
int x = n * n;
System.out.println(x);
}

//New way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
list.stream().map((x) -> x*x).forEach(System.out::println);


//Old way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
int sum = 0;
for(Integer n : list) {
int x = n * n;
sum = sum + x;
}
System.out.println(sum);

//New way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get();
System.out.println(sum);

findAny

1
2
3
4
5
 Optional<A> optional = list().stream().filter(e ->
(e.getType() == tag.getType())).findAny();
if (!optional.isPresent()) {

}

collect

1
2
tagList = list.parallelStream().filter(e ->e.getType() == tag.getType()
).collect(Collectors.toList());

map

1
List<String> list = tagList.stream().map(Tag::getValue).collect(Collectors.toList());

limit

1
2
3
4
5
6
7
8
9
Stream.iterate(0, i -> i + 1).limit(tagList.size()).forEach(
i -> {
if (i == 0) {
} else {
}
if (i == (tagList.size() - 1)) {
}
}
);

forEach

1
2
3
tagList().forEach(e -> {
parse(e);
});

comparing

1
list.sort(Comparator.comparing(e -> e.getPriority()));

parallelStream

1
2
3
4
5
public Ele getEle() {
return ist().parallelStream()
.filter(e -> Objects.equals("", ""))
.findAny().orElse(null);
}

of

1
2
3
4
5
Stream.of("张三","李四","王二","张四五")
.filter(x -> x.startsWith("张"))
.mapToInt(String::length)
.max()
.ifPresent(System.out::println);

removeIf 移除元素

1
2
3
4
5
6
7
8
9
10
11
12
13
List<String> str1 = new ArrayList<String>();
str1.add("A");
str1.add("B");
str1.add("C");
str1.add("D");

List<String> str2 = new ArrayList<String>();
str2.add("D");
str2.add("E");

str1.removeIf(x -> str2.contains(x));

str1.forEach(System.out::println);
------ 本文结束------

本文标题:Java Lambda用法

文章作者:Perkins

发布时间:2019年08月02日

原始链接:https://perkins4j2.github.io/posts/15864/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。