FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
java-base/java-8future/src/test/java/SupplierTest.java at master · singgel/java-base · GitHub
singgel
/
java-base
Public
Notifications
You must be signed in to change notification settings
Fork
28
Star
39
Code
Issues
0
Pull requests
6
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
java-base
/
java-8future
/
src
/
test
/
java
/
SupplierTest.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
70 lines (59 loc) · 2.12 KB
Breadcrumbs
java-base
/
java-8future
/
src
/
test
/
java
/
SupplierTest.java
Copy path
File metadata and controls
70 lines (59 loc) · 2.12 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
org
.
junit
.
Test
;
import
java
.
util
.
Optional
;
import
java
.
util
.
Random
;
import
java
.
util
.
function
.
Supplier
;
import
java
.
util
.
stream
.
Stream
;
/**
* @author heks
* @description: TODO
* @date 2020/11/11
*/
public
class
SupplierTest
{
/**
* Supplier接口测试,supplier相当一个容器或者变量,可以存储值
*/
@
Test
public
void
test_Supplier
() {
//① 使用Supplier接口实现方法,只有一个get方法,无参数,返回一个值
Supplier
<
Integer
>
supplier
=
new
Supplier
<
Integer
>() {
@
Override
public
Integer
get
() {
//返回一个随机值
return
new
Random
().
nextInt
();
}
};
System
.
out
.
println
(
supplier
.
get
());
System
.
out
.
println
(
"********************"
);
//② 使用lambda表达式,
supplier
= () ->
new
Random
().
nextInt
();
System
.
out
.
println
(
supplier
.
get
());
System
.
out
.
println
(
"********************"
);
//③ 使用方法引用
Supplier
<
Double
>
supplier2
=
Math
::
random
;
System
.
out
.
println
(
supplier2
.
get
());
}
/**
* Supplier接口测试2,使用需要Supplier的接口方法
*/
@
Test
public
void
test_Supplier2
() {
Stream
<
Integer
>
stream
=
Stream
.
of
(
1
,
2
,
3
,
4
,
5
);
//返回一个optional对象
Optional
<
Integer
>
first
=
stream
.
filter
(
i
->
i
>
4
)
.
findFirst
();
//optional对象有需要Supplier接口的方法
//orElse,如果first中存在数,就返回这个数,如果不存在,就放回传入的数
System
.
out
.
println
(
first
.
orElse
(
1
));
System
.
out
.
println
(
first
.
orElse
(
7
));
System
.
out
.
println
(
"********************"
);
Supplier
<
Integer
>
supplier
=
new
Supplier
<
Integer
>() {
@
Override
public
Integer
get
() {
//返回一个随机值
return
new
Random
().
nextInt
();
}
};
//orElseGet,如果first中存在数,就返回这个数,如果不存在,就返回supplier返回的值
System
.
out
.
println
(
first
.
orElseGet
(
supplier
));
}
}
Back
|
FazBrowse Home
|
New Git URL