语法格式1:
无参数无返回值
@Test
public void test1(){
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("hello world");
}
};
r.run();
System.out.println("==================");
Runnable r1 = () -> System.out.println("hello lambda");
r1.run();
}
@Test
public void test1(){
final int num = 0;//jdk 1.7 : 前面必须加final
int num1 = 0;//jdk 1.8 : 可以不加final但是默认是final
//匿名内部类
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("hello world"+num);//num++会报错
}
};
r.run();
System.out.println("==================");
Runnable r1 = () -> System.out.println("hello lambda"+num1);//num1++会报错
r1.run();
}
语法格式2:
一个参数无返回值
@Test
public void test2(){
Consumer<String> con = (x) -> System.out.println(x);
con.accept("haha");
}
@Test
public void test3(){
Comparator<Integer> com = (x,y) -> {
System.out.println("函数式接口");
return Integer.compare(x,y);
};
}
@Test
public void test3(){
Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
}
//JVM编译器根据上下文进行数据类型推断的例子
@Test
public void test5(){
String[] strs = {"aa","aab"};
List<String> list = new ArrayList<>();
show(new HashMap<>());
}
public void show(Map<String,String> map){
}
@FunctionalInterface
public interface MyFun {
public Integer getValue(Integer num);
}
@Test
public void test6(){
Integer num = operation(100, (x) -> x * x);
System.out.println(num);
System.out.println(operation(200,(y) -> y + 200));
}
public Integer operation(Integer num , MyFun mf){
return mf.getValue(num);
}
练习:
public class TestLambda {
List<Employee> emps = Arrays.asList(
new Employee("张3",18,100001),
new Employee("张4",19,110001),
new Employee("张5",12,1001),
new Employee("张6",68,101),
new Employee("张7",68,11)
);
@Test
public void test1(){
Collections.sort(emps,
(e1 , e2) -> e1.getAge() == e2.getAge() ? e1.getName().compareTo(e2.getName()) : Integer.compare(e1.getAge(),e2.getAge()));
for (Employee emp : emps){
System.out.println(emp);
}
}
}
@FunctionalInterface
public interface MyFunction {
public String getValue(String str);
}
//需求:处理字符串
public String strHandler(String str , MyFunction mf){
return mf.getValue(str);
}
@Test
public void test2(){
String trimStr = strHandler("\t\t\t 哈哈哈哈哈哈 ", (str) -> str.trim());
System.out.println(trimStr);
String upperStr = strHandler("abasuaia", (str) -> str.toUpperCase());
System.out.println(upperStr);
String newStr = strHandler("你好你好你好你好", (str) -> str.substring(2, 5));
System.out.println(newStr);
}
@FunctionalInterface
public interface MyFunction2<T,R> {
public R getValue(T t1 , T t2);
}
public void op(Long l1 , Long l2 , MyFunction2<Long,Long> mf){
System.out.println(mf.getValue(l1,l2));
}
@Test
public void test3(){
op(100L,200L,(x , y) -> x + y);
op(100L,200L,(x , y) -> x * y);
}
扩展