Java 8 为什么要使用Lambda表达式

>看例子

对于员工Employee(成员:name、age、salary)

public class Testlambda {

	// 需求:获取当前员工年龄大于35 的员工
	// 需求:获取点钱员工工资大于5000的员工
	// 需求;......
	// 下面这段会产生大量的冗余代码,怎么办?

	List employees = Arrays.asList(new Employee("张三", 18, 9999.99), new Employee("李四", 50, 6999.99),
			new Employee("王五", 35, 9999.99), new Employee("赵六", 22, 5999.99), new Employee("田七", 26, 3999.99));

	public List filterEmployee(List list) {
		List emps = new ArrayList();
		for (Employee emp : list) {
			if (emp.getAge() > 35) {
				emps.add(emp);
			}
		}
		return emps;
	}

	// 优化方式一:设计模式(策略模式)
	public List fileterEmployee(List list, MyPredicate mp) {
		List emps = new ArrayList();
		for (Employee emp : list) {
			if (mp.test(emp)) {
				emps.add(emp);
			}
		}
		return emps;
	}

	@Test
	public void test1() {
		List list = fileterEmployee(employees, new FilterEmployeeByAge());
		for (Employee employee : list) {
			System.out.println(employee);
		}
		System.out.println("-------------------");
		List list2 = fileterEmployee(employees, new FilterEmployeeBySalary());
		for (Employee employee : list2) {
			System.out.println(employee);
		}
	}

	// 优化方式二:匿名内部类
	@Test
	public void test2() {
		List list = fileterEmployee(employees, new MyPredicate() {

			@Override
			public boolean test(Employee t) {
				return t.getAge() > 35;
			}
		});
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}

	// 优化方式三:lambda表达式
	@Test
	public void test3() {
		List list = fileterEmployee(employees, (e) -> e.getSalary() >= 5000);
		list.forEach(System.out::println);
	}

	// 优化方式四:Stream API(不使用策略模式)
	@Test
	public void test4() {
		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);
	}

}

 >策略模式用例

public interface MyPredicate {

	public boolean test(T t);

}
public class FilterEmployeeBySalary implements MyPredicate {

	@Override
	public boolean test(Employee t) {
		return t.getSalary() >= 5000;
	}

}
public class FilterEmployeeByAge implements MyPredicate {

	@Override
	public boolean test(Employee t) {
		return t.getAge() > 35;
	}

}

 

 

 

你可能感兴趣的:(Java新特性)