需求:获取当前公司中年龄大于35岁的员工信息
public class LambdaTest {
List<Employee> employeeList = Arrays.asList(
new Employee("张三",45,999.99),
new Employee("李四",38,666.66),
new Employee("王五",32,555.55),
new Employee("赵六",25,333.33),
new Employee("田七",18,111.11)
);
//需求:获取当前公司中年龄大于35岁的员工信息
public List<Employee> filterEmployeeList(List<Employee> employeeList){
List<Employee> filterList = new ArrayList<>();
for (Employee employee :employeeList) {
if (employee.getAge() > 35) {
filterList.add(employee);
}
}
return filterList;
}
//需求:获取当前公司工资大于500的员工信息
public List<Employee> filterEmployeeSalaryList(List<Employee> employeeList){
List<Employee> filterList = new ArrayList<>();
for (Employee employee :employeeList) {
if (employee.getSalary() > 500) {
filterList.add(employee);
}
}
return filterList;
}
@Test
public void testEmployee(){
List<Employee> filterList = filterEmployeeList(employeeList);
for (Employee employee:filterList) {
System.out.println(employee.toString());
}
}
}
优化:策略设计模式,给什么策略就按什么策略进行过滤,但每一个策略就需要一个类去实现接口
public interface MyPredicate<T> {
public boolean test(T t);
}
public class FilterEmployeeByAge implements MyPredicate<Employee>{
@Override
public boolean test(Employee employee) {
return employee.getAge()>35;
}
}
public class FilterEmployeeBySalary implements MyPredicate<Employee>{
@Override
public boolean test(Employee employee) {
return employee.getSalary() > 500;
}
}
public List<Employee> filterEmployee(List<Employee> list,MyPredicate<Employee> mp) {
List<Employee> employeeList = new ArrayList<>();
for (Employee employee:list) {
if (mp.test(employee)) {
employeeList.add(employee);
}
}
return employeeList;
}
@Test
public void filterEmployee(){
List<Employee> list = filterEmployee(employeeList,new FilterEmployeeByAge());
for (Employee employee : list) {
System.out.println(employee.toString());
}
System.out.println("-------------------");
List<Employee> list2 = filterEmployee(employeeList,new FilterEmployeeBySalary());
for (Employee employee : list2) {
System.out.println(employee.toString());
}
}
优化方式二:匿名内部类,只需要一个接口,不用每次都单独创建一个类去实现接口
@Test
public void innerClassCTest(){
List<Employee> list = filterEmployee(employeeList, new MyPredicate<Employee>() {
@Override
public boolean test(Employee employee) {
return employee.getSalary() > 500;
}
});
for (Employee employee :list) {
System.out.println(employee);
}
}
优化方式三:lambda表达式
@Test
public void lambdaTest(){
List<Employee> list = filterEmployee(employeeList,employee -> employee.getSalary()>500);
for (Employee employee: list) {
System.out.println(employee.toString());
}
}
优化方式四:Stream API
@Test
public void streamApiTest(){
employeeList.stream().filter(employee -> employee.getSalary()>500)
.forEach(System.out::println);
}