1+ package com .rice .java8 .samples .lambda ;
2+
3+ import com .rice .java8 .samples .test .AbstractBaseTest ;
4+ import org .junit .Test ;
5+
6+ /**
7+ * 测验3.4:函数式接口 对于下列函数描述符(即Lambda表达式的签名),你会使用哪些函数式接口?在表3-2中
8+ * 可以找到大部分答案。作为进一步练习,请构造一个可以利用这些函数式接口的有效Lambda 表达式:
9+ * (1) T->R
10+ * (2) (int, int)->int
11+ * (3) T->void
12+ * (4) ()->T
13+ * (5) (T, U)->R
14+ */
15+ public class Java8InActionTest extends AbstractBaseTest {
16+
17+ @ Test
18+ public void testFun1 () {
19+ Fun1 f1 = (t ) -> t .hashCode ();
20+ System .out .println ("T -> R" );
21+ System .out .println (f1 .whatEver ("I'm T Object! return value it's my hascode! " ));
22+ }
23+
24+ @ Test
25+ public void testFun2 () {
26+ Fun2 f2 = (a , b ) -> a + b + 100 ;
27+ System .out .println ("(int, int)->int" );
28+ System .out .println (f2 .whatEver_JustASign (1 , 2 ));
29+ }
30+
31+ @ Test
32+ public void testFun3 () {
33+ Fun3 f3 = (t ) -> System .out .println ("T -> void" );
34+ f3 .xxx ("what ever value pass in " );
35+ }
36+
37+ @ Test
38+ public void testFun4 () {
39+ Fun4 <String > f4 = () -> "only String can return" ;
40+ System .out .println (" ()->T " );
41+ System .out .println (f4 .aaa ());
42+ }
43+
44+ @ Test
45+ public void testFun5 () {
46+ Fun5 <String ,Integer ,Long > f5 = (t ,u ) -> (long )(t .length () * u );
47+ System .out .println (" (T, U)->R " );
48+ System .out .println (f5 .bbb ("hello" ,10 ));
49+ }
50+
51+ }
52+
53+
54+ /**
55+ * T->R
56+ *
57+ * @param <T>
58+ * @param <R>
59+ */
60+ @ FunctionalInterface
61+ interface Fun1 <T , R > {
62+ R whatEver (T t );
63+ }
64+
65+ /**
66+ * (int, int)->int
67+ */
68+ @ FunctionalInterface
69+ interface Fun2 {
70+ int whatEver_JustASign (int a , int b );
71+ }
72+
73+ /**
74+ * T->void
75+ */
76+ @ FunctionalInterface
77+ interface Fun3 <T > {
78+ void xxx (T t );
79+ }
80+
81+ /**
82+ * ()->T
83+ */
84+ @ FunctionalInterface
85+ interface Fun4 <T > {
86+ T aaa ();
87+ }
88+
89+ /**
90+ * (T, U)->R
91+ */
92+ @ FunctionalInterface
93+ interface Fun5 <T , U , R > {
94+ R bbb (T t , U u );
95+ }
0 commit comments