1.调用Collections.sort()方法,通过定制排序比较两个Employee(先按年龄比,年龄相同按姓名比),使用Lambda作为参数传递。
LambdaTest1.java
public class LambdaTest1 {
List<Employee> employees = Arrays.asList(
new Employee("张三",18,10000.00),
new Employee("李四",22,34560.00),
new Employee("王五",22,66666.66),
new Employee("赵六",26,78788.00),
new Employee("田七",28,88999.00)
);
@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 employee : employees) {
System.out.println(employee);
}
}
}
运行结果
2.①声明函数式接口,接口中声明抽象方法,public string getValue(String str);②声明类Testlambda,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值。③再将一个字符串从第3个索引位置进行截取子串。
MyFunction.java
package com.uos.jdk8;
@FunctionalInterface
public interface MyFunction {
public String getValue(String str);
}
TestLambda2.java
public class TestLambda2{
// 需求:用于处理字符串
public String strHandler(String str,MyFunction mf){
return mf.getValue(str);
}
@Test
public void test2(){
// 将字符串转换为大写
String upperStr = strHandler("hello lambda", (str) -> str.toUpperCase());
System.out.println(upperStr);
// 截取指定的字符串
String newStr = strHandler("你好,Lambda表达式", (str -> str.substring(3)));
System.out.println(newStr);
}
}
运行结果
3.①声明一个带两个泛型的函数式接口,泛型类型为<T,R>T为参数,R为返回值②接口中声明对应抽象方法。③在TestLambda类中声明方法,使用接口作为参数,计算两个long型参数的和。④再计算两个long型参数的乘积。
MyFunction2.java
package com.uos.jdk8;
@FunctionalInterface
public interface MyFunction2<T,R> {
public R getValue(T t1,T t2);
}
TestLambda3.java
public class TestLambda3{
@Test
public void test3(){
// 加法操作
Long num1 = longHandler(100L, 200L, (x, y) -> x + y);
System.out.println(num1);
// 乘法操作
Long num2 = longHandler(300L, 400L, (x, y) -> x * y);
System.out.println(num2);
}
// 对两个long型数据进行处理
public Long longHandler(Long num1,Long num2,MyFunction2<Long,Long> mf){
return mf.getValue(num1,num2);
}
}
运行结果