使用Lambda表达式处理简单的业务

it2023-04-01  71

定义 函数式接口 一种只含有一个抽象方法声明的接口 可以使用匿名内部类来实例化函数式接口的对象 通过Lambda表达式可以进一步简化代码 语法

(paramenters) -> expression (paramenters) -> {statements;}

步骤: 1.新建一个接口 2.新建一个Java类,继承创建的接口,并根据业务需求定义数据类型 3.创建Java测试类,进行功能实现 实例: 1.根据学历和年龄来确定工资 1)新建OperationInterface接口

public interface OperationInterface { public Integer salary (String a,Integer b); }

2)新建OperationInterfaceImpl类,定义学历String类型,年龄Integer类型

public class OperationInterfaceImpl implements OperationInterface{ @Override public Integer salary(String a, Integer b) { return null; } }

3)新建TestSalary类

public class TestSalary { public static void main(String[] args) { OperationInterface sal = (String a,Integer b) -> { if (a.equals("初中")&& b == 20) { return 2000; } else if (a.equals("高中")&& b == 20) { return 2200; } else if (a.equals("大专")&& b == 21) { return 3000; } else if (a.equals("本科")&& b == 22) { return 3300; } else { return 0; } }; System.out.println(sal.salary("本科",22)); } }

运行结果如下

2.判断字符串是否包含字符a、字符b,是则分别返回1和0,否则,返回0 1)创建Operation接口

public interface Operation { public Integer operation(String a); }

2)创建OperationIml类,继承Operation接口

public class OperationIml implements Operation{ @Override public Integer operation(String a) { return null; } }

3)创建TestChar测试类

public class TestChar { public static void main(String[] args) { Operation opp = (String a) -> { if (a.contains("a")) { return 1; } else if (a.contains("b")) { return 0; } else { return -1; } }; System.out.println(opp.operation("abdfe")); } }

测试结果如下

3.用lambda表达式进行两个数之间的四则运算 1)创建OperationInterface接口

public interface OperationInterface { public Integer operation(Integer a,Integer b); }

2)创建OperationInterfaceImpl类,继承OperationInterface接口

public class OperationInterfaceImpl implements OperationInterface{ @Override public Integer operation(Integer a, Integer b) { return a+b; } }

3)创建TestDemo测试类

public class TestDemo { public static void main(String[] args) { OperationInterface add = (Integer a,Integer b) -> a+b; OperationInterface jian = (Integer a,Integer b) -> a-b; OperationInterface ji = (Integer a,Integer b) -> a*b; // Integer sum2 = ji.operation(10,20); // System.out.println(sum2); TestDemo demo = new TestDemo(); Integer result = demo.getResult(20, 10, add); System.out.println(result); // OperationInterface operationInterface = new OperationInterfaceImpl(); // Integer sum = operationInterface.operation(10,10); // System.out.println(sum); } public Integer getResult(Integer a,Integer b,OperationInterface operationInterface) { return operationInterface.operation(a,b); }

测试结果如下

最新回复(0)