Java8-新特性

 

1.Lambda表达式

为什么使用Lambda表达式?

Lambda 是一个匿名函数,我们可以把Lambda表达式理解为是一段可以传递的代码。可以写出更简洁、高效的代码。

(1).Lambda初体验
我们先来看一段匿名内部类的代码 使用Lambda表达式后的样子
        //匿名内部类         Comparator<Integer> com = new Comparator<Integer>() {             @Override             public int compare(Integer o1, Integer o2) {                 return Integer.compare(o1, o2);             }         };                  TreeSet<Integer> treeSet = new TreeSet<>(com);          //使用了Lambda式后的匿名内部类         Comparator<Integer> com = (x,y) -> Integer.compare(x, y);         TreeSet<Integer> treeSet = new TreeSet<>(com);

准备工作: 创建一个Employee 实体类

public class Employee {          private String name;     private Integer age;     private Double salary;     private Status status;          //get\set\equals\hashcode方法     `````````````     `````````````     public enum Status{         FREE,BUSY,VACATION;     }           }

接下来假设我们有一个需求: 获取公司员工年龄大于等于35的员工信息

那么我们可能需要这么干

public class TestLambda {          List<Employee> list = Arrays.asList(             new Employee("张三", 18, 9999.99),             new Employee("李四", 38, 5555.99),             new Employee("王五", 50, 6666.99),             new Employee("赵六", 16, 3333.33),             new Employee("田七", 8, 7777.77)     );     //传统方式     @Test     public void test1(){         List<Employee> empList = filterEmployeeByAge(list);                  for (Employee e:empList) {             System.out.println(e);         }              }          public List<Employee> filterEmployeeByAge(List<Employee> list){         List<Employee> emps = new ArrayList<>();                  for(Employee e:list){             if(e != null && e.getAge() >= 35)                 emps.add(e);         }         return emps;     }      }

然后来了第二个需求:获取工资大于的5000的员工,而此时原来的方法可能被别的方法引用着

所以我们又这么干,新加了一个方法满足第二个需求

public List<Employee> filterEmployeeBySalary(List<Employee> list){         List<Employee> emps = new ArrayList<>();                  for(Employee e:list){             if(e != null && e.getSalary() >= 5000)                 emps.add(e);         }         return emps; }

那么现在有一个问题,如果接下来有第三、第四或第五个需求,我们需要创建第三、第四、第五个方法么

这好像是一件十分愚蠢的事

所以接下来我们使用策略模式来做一次优化 , 那这跟Lambda表达式有半毛钱关系么,别急,耐心看下去


                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信