A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈冠祖 初级黑马   /  2018-11-22 13:25  /  467 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文



在Java8中引入了一个新的操作符“->”,该操作符称为箭头操作符或Lambda操作符。
左侧:Lambda表示式的参数列表
右侧:Lambda表达式中所要执行的功能



语法格式



1.无参数,无返回值()-> System.out.print(“Hello Word”);

示例如下:

@Test
public void test1(){
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Hello Word");
        }
    };
    r.run();
    System.out.print("===============================");
    Runnable r1 = () -> System.out.print("Hello Word");
    r1.run();
}
12345678910111213



2.一个参数,无返回值(x)-> System.out.print(x);

@Test
public void test2(){
    Consumer<String> con = (x) -> System.out.println(x);
    con.accept("Hello Word");
}
12345

如果只有一个参数,无返回值可以省略小括号不写。



3.两个参数,有返回值,并且有多条执行语句

@Test
public void test3(){
    Comparator<Integer> com = (x,y) ->{
        System.out.println("函数式接口");
        return Integer.compare(x,y);
    };
    int max = com.compare(4,5);
    System.out.println(max);
}
123456789



4.如果只有一条返回语句

@Test
public void test4(){
    Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
}
1234



4.lambda表达式中的参数类型可以省略不写,JVM可以根据上下文推断出类型



Lambda表达式需要函数式接口的支持。



函数式接口

接口中只有一个抽象方法的接口,就叫函数式接口。可以使用注解@FunctionalInterface检查是否为函数式接口。

@FunctionalInterface
public interface MyPredicat <T>{
    public boolean test(T t);
}
1234

示例如下:
1.定义一个函数式接口

@FunctionalInterface
public interface MyFun {
    public Integer getValue(Integer num);
}
1234

2.定义一个方法,方法的参数为函数式接口

public Integer operation(Integer num,MyFun mf){
        return mf.getValue(num);
    }
123

3.使用Lambda表达式

@Test
public void test5(){
    Integer num = operation(100,(x)-> x*x);
    System.out.println(num);
}
12345

Lambda表达式左侧是函数式接口的参数,右侧是函数式接口的实现。



Lambda练习

将集合中的员工排序,按照年龄从小到大排序,如果年龄相同就按照名称排序

public class TestLambda {
    List<Employee> emps = Arrays.asList(
            new Employee("张三",13,9999.99),
            new Employee("李四",67,444.44),
            new Employee("王五",45,55.55),
            new Employee("赵六",45,6666.66)
    );
    @Test
    public void test1(){
        Collections.sort(emps,(e1,e2) -> {
            if(e1.getAge() == e2.getAge()){
                return e1.getName().compareTo(e2.getName());
            }else{
                return Integer.compare(e1.getAge(),e2.getAge());
            }
        });
        for(Employee emp:emps){
            System.out.println(emp);
        }
    }
}


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马