1.调用Collection.sort()方法,通过定制排序比较两个Employee(先按年龄,年龄相同按姓名比)。
List<Employee> employees = Arrays.asList(
new Employee("张小", 19, 1999.99),
new Employee("李而", 18, 2999.99),
new Employee("张三", 20, 3999.99),
new Employee("张四", 50, 4999.99),
new Employee("王五", 38, 5555.55),
new Employee("赵六", 30, 6666.66),
new Employee("田七", 21, 7777.77)
);
@Test
public void test1(){
Collections.sort(employees,(e1,e2)->{
if (e1.getAge()==e2.getAge()){
return e1.getName().compareTo(e2.getName());
}else {
return Integer.compare(e1.getAge(),e2.getAge());
}
});
for (Employee emp: employees) {
System.out.println(emp);
}
}
2.声明函数式接口,接口中声明抽象方法,public String getValue();
- 声明类TestLambda,类中编写方法使用接口作为参数,将每一个字符品转换成大写,并作为方法的返回值
- 再将一个字符串的第2个和第4个索引位置进行截取子串
@Test
public void test2(){
String trimStr = strHandler("\t\t\t 我大北大荒威武 ", (str) -> str.trim());
System.out.println(trimStr);
String upperStr = strHandler("abcdef", (str) -> str.toUpperCase());
System.out.println(upperStr);
String newStr = strHandler("我大北大荒威武", (str) -> str.substring(2, 5));
System.out.println(newStr);
}
public String strHandler(String str, MyFunction myFunction){
return myFunction.getValue(str);
}
3.声明一个带两个泛型的函数式接口,泛型类型为<T,R> T为参数,R为返回值
- 接口中声明对应抽象方法
- 在TestLambda类中声明方法,使得接口作为参数,计算两个long型参数的和
- 再计算两个long型参数的乘积
@Test
public void test3(){
op(100L,200L,(x,y)->x+y);
op(100L,200L,(x,y)->x*y);
}
public void op(Long L1, Long L2, MyFunctionLong<Long,Long> mf){
System.out.println(mf.getValue(L1,L2));
}