1. 程式人生 > 實用技巧 >java8新特性之(一)lambda表示式

java8新特性之(一)lambda表示式

java8新特性

  速度更快;

  程式碼更少;

  強大的streamAPI;

  便於並行;

  最大減少空指標異常Optional;

  其中最核心的lambda表示式和StreamAPI。

lambda表示式

  lambda是一個匿名函式,可以把lambda表示式理解為一段可以傳遞的程式碼。可以寫出更簡潔更靈活的程式碼,使java語言的表達能力得到了提升。

eg: 一個employee類,通過lambda篩選出年齡大於40的employee物件

1.Employee實體類

public class Employee {
    private String userName;
    
private int age; private int salary; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }
public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public String toString() { return "Employee{" + "userName='" + userName + '\'' + ", age=" + age + ", salary=" + salary + '}'; } }

2.函式式介面

public interface MyPredicate {
    public boolean test(Employee employee);
}

3.lambda實現

public class EmployeeMain {
    public List<Employee> filterEmployee(List<Employee> employees,MyPredicate mp){
            List<Employee> result = new ArrayList<>();
        for (Employee employee : employees) {
            if(mp.test(employee)){
                result.add(employee);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        for(int i = 0;i<5;i++){
            Employee  employee = new Employee();
            employee.setUserName("zhangsan"+i);
            employee.setAge(48+i);
            employee.setSalary(2445+10*i);
            employees.add(employee);
        }
        EmployeeMain employeeMain = new EmployeeMain();
        System.out.println("--------------------------------");
        //lambda實現
        List<Employee> employeesByLambda = employeeMain.filterEmployee(employees,(e)->e.getSalary()>2450);
      for (Employee employee : employeesByLambda) {
            System.out.println(employee.toString());
        }

        System.out.println("--------------------------------");
        //lambda按age篩選實現
        List<Employee> employeesByLambdaWithAge = employeeMain.filterEmployee(employees,(e)-> e.getAge()>50);
        for (Employee employee : employeesByLambdaWithAge) {
            System.out.println(employee.toString());
        }
    }
}

4.執行結果:

lambda表示式基本語法

java8中引入了一個新的操作符“->”,該操作符稱為箭頭操作符lambda操作符,箭頭操作符將lambda表示式拆分為兩部分。其中,lambda操作符左側為引數列表,右側為lambda表示式所執行的功能,即lambda體。lambda需要宣告函式式介面,函式式介面即只有一個抽象方法的介面。

語法格式大致分為:

1.無引數,無返回值

public static void main(String[] args) {
       /**
         *  無引數,無返回值
         */
        Runnable runnable = ()-> System.out.println("執行緒lambda表示式");
        runnable.run();
}

2.一個引數,無返回值

public static void main(String[] args) {
           /**
         * 一個引數,無返回值
         */
        Consumer<Integer> consumer = x-> System.out.println(x);
        consumer.accept(10);
}    

3.兩個引數,有返回值,且只有一條實現語句

public static void main(String[] args) { 
       /**
         * 兩個引數,且有返回值,只有一條實現語句
         */
        System.out.println("------------------------");
        Comparator<Integer> comparator = (x,y)->Integer.compare(x,y);
        System.out.println(comparator.compare(10,20));
}

4.兩個引數,有返回值,且只有多條實現語句

public static void main(String[] args) {
         Comparator<Integer> comparator1 = (x,y)->{
            System.out.println("多條語句");
            return Integer.compare(x,y);
        };
        System.out.println(comparator1.compare(11,2));
}

eg:使用lambda表示式實現x的平方

1.宣告函式式介面

@FunctionalInterface //宣告為函式式介面
public interface MyFun {
    public Integer getValue(int num);
}

2.定義一個operation函式

public class TestLambda {
    public Integer operation(int num,MyFun myFun){
        return myFun.getValue(num);
    }

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