Java8新特性之Lambda表達式(一)

新建一個springboot項目:可按https://blog.csdn.net/ZW_888666/article/details/99824347操作

 創建後續學習中需要用到的Employee實體類:

package lambda;

import java.util.Objects;

public class Employee {

    private String name;
    private int age;
    private double salary;
    private Status status;   //枚舉型

    //生成無參構造器
    public Employee() {
    }

    public Employee(String name) {
        this.name = name;
    }

    public Employee(int age) {
        this.age = age;
    }

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    //生成全參構造器
    public Employee(String name, int age, double salary, Status status) {
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.status = status;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Employee)) return false;
        Employee employee = (Employee) o;
        return getAge() == employee.getAge() &&
                Double.compare(employee.getSalary(), getSalary()) == 0 &&
                getName().equals(employee.getName());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getName(), getAge(), getSalary());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                ", status=" + status +
                '}';
    }

    public enum Status{
        FREE,
        BUSY,
        VOCATION
    }
}
FilterEmployeeByAge類:
package lambda;

public class FilterEmployeeByAge implements Mypredicate<Employee> {
    @Override
    public boolean test(Employee employee) {
        return employee.getAge() >= 35;
    }
}
FilterEmployeeBySalary類:
package lambda;

public class FilterEmployeeBySalary implements Mypredicate<Employee> {

    @Override
    public boolean test(Employee employee) {
        return employee.getSalary() >= 5000;
    }
}
MyFun接口:
package lambda;

@FunctionalInterface
public interface MyFun<T> {
    public Integer getValue(Integer my);
}
MyFunction接口:
package lambda;


@FunctionalInterface
public interface MyFunction {

   public String getValue(String str) ;

}
MyFunction2接口:
package lambda;

/**
 * @author qiuxin
 * @date 2020/02/22
 **/
public interface MyFunction2<T, R> {

    public R getValue(T t1, T t2);

}
Mypredicate接口:
package lambda;

public interface Mypredicate<T> {
    public boolean test(T t);
}

準備工作做好了,可以開始寫有關lambda的測試,,,

  • 爲什麼要使用lambda:
    package lambda;
    
    import org.junit.Test;
    
    import java.util.*;
    
    public class TestLambda1 {
    
        //原來的匿名內部類
        @Test
        public void test1() {
            Comparator<Integer> com = new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return Integer.compare(o1, o2);
                }
            };
            TreeSet<Integer> ts = new TreeSet<>(com);
        }
    
        //Lambda表達式
        @Test
        public void test2() {
            Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
            TreeSet<Integer> ts = new TreeSet<>(com);
        }
    
    
        @Test
        public void test3() {
            List<Employee> list = filter(employees);
            for (Employee employee : list) {
                System.out.println(employee);
            }
        }
    
        List<Employee> employees = Arrays.asList(
                new Employee("張三", 25, 9000),
                new Employee("李四", 38, 10000),
                new Employee("王曉", 45, 12000),
                new Employee("李華", 28, 9500),
                new Employee("花花", 22, 8000)
        );
    
        //需求:獲取當前公司中員工年齡大於35的數,有可能附加多個條件進行篩選
        public List<Employee> filter(List<Employee> list) {
            List<Employee> emps = new ArrayList<>();
            for (Employee emp : list) {
                if (emp.getAge() >= 35) {
                    emps.add(emp);
                }
            }
            return emps;
        }
    
        @Test
        public void test4() {
            List<Employee> employee = filterEmployee(employees, new FilterEmployeeByAge());
            for (Employee employee1 : employee) {
                System.out.println(employee1);
            }
    
            List<Employee> employees0 = filterEmployee(employees, new FilterEmployeeBySalary());
            for (Employee employee1 : employees0) {
                System.out.println(employee1);
            }
        }
    
        //優化方式一:策略設計模式
        public List<Employee> filterEmployee(List<Employee> list, Mypredicate<Employee> mp) {
            List<Employee> emps = new ArrayList<>();
            for (Employee employee : list) {
                if (mp.test(employee)) {
                    emps.add(employee);
                }
            }
            return emps;
        }
    
        //優化方式二:匿名內部類
        @Test
        public void test5() {
            List<Employee> result = new ArrayList<>();
            List<Employee> employees0 = filterEmployee(employees, new Mypredicate<Employee>() {
                @Override
                public boolean test(Employee employee) {
                    return employee.getSalary() >= 5000;
                }
            });
            for (Employee employee : employees0) {
                System.out.println(employee);
                result.add(employee);
            }
        }
    
        //優化方式三:Lambda表達式
        @Test
        public void test6() {
            List<Employee> result = new ArrayList<>();
            List<Employee> employees0 = filterEmployee(employees, (e) -> e.getSalary() >= 5000);
            for (Employee employee : employees0) {
                System.out.println(employee);
                result.add(employee);
            }
        }
    
        //優化方式四:Stream API
        @Test
        public void test7(){
            employees.stream()
                    .filter((e)->e.getSalary()>=5000)
                    .limit(2)
                    .forEach(System.out::println);
            System.out.println("------------------------");
            employees.stream()
                    .map(Employee::getName)
                    .forEach(System.out::println);
        }
    
    }
    
    

    代碼更簡潔可觀

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章