-
Notifications
You must be signed in to change notification settings - Fork 732
Expand file tree
/
Copy pathLambdaTest.java
More file actions
55 lines (43 loc) · 1.73 KB
/
LambdaTest.java
File metadata and controls
55 lines (43 loc) · 1.73 KB
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
package javaprogramming.commonmistakes.java8;
import org.junit.Test;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class LambdaTest {
@Test
public void lambdavsanonymousclass() {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello1");
}
}).start();
new Thread(() -> System.out.println("hello2")).start();
}
@Test
public void functionalInterfaces() {
//可以看一下java.util.function包
Supplier<String> supplier = String::new;
Supplier<String> stringSupplier = () -> "OK";
//Predicate的例子
Predicate<Integer> positiveNumber = i -> i > 0;
Predicate<Integer> evenNumber = i -> i % 2 == 0;
assertTrue(positiveNumber.and(evenNumber).test(2));
//Consumer的例子,输出两行abcdefg
Consumer<String> println = System.out::println;
println.andThen(println).accept("abcdefg");
//Function的例子
Function<String, String> upperCase = String::toUpperCase;
Function<String, String> duplicate = s -> s.concat(s);
assertThat(upperCase.andThen(duplicate).apply("test"), is("TESTTEST"));
//Supplier的例子
Supplier<Integer> random = () -> ThreadLocalRandom.current().nextInt();
System.out.println(random.get());
//BinaryOperator
BinaryOperator<Integer> add = Integer::sum;
BinaryOperator<Integer> subtraction = (a, b) -> a - b;
assertThat(subtraction.apply(add.apply(1, 2), 3), is(0));
}
}