1. 调用 Collections.sort()方法,通过定制排序比较两个 Employee(先按 年龄比,年龄相同按姓名 比),使用 Lambda 表达式作为参数传递。
public class Exer1 {
public static void main(String[] args) {
Employee e1 = new Employee(1001, "马化腾", 34, 6000.38);
Employee e2 = new Employee(1002, "马云", 12, 9876.12);
Employee e3 = new Employee(1005, "李彦宏", 65, 5555.32);
List<Employee> list = new ArrayList<>();
list.add(e1);
list.add(e2);
list.add(e3);
Comparator<Employee> com = (a,b) -> {
int differ = Integer.compare(a.getAge(), b.getAge());
if(differ==0) {
return a.getName().compareTo(b.getName());
}
return differ;
};
System.out.println(list);
Collections.sort(list,com);
System.out.println(list);
}
}
2. ① 声 明 函 数 式 接 口 , 接 口 中 声 明 抽 象 方 法 : public String getValue(String str); ②声明类 LambdaTest,类中编写方法使用接口作为参数,将一个 字符串转换成大写,并作为方法的返回值。 ③再将一个字符串的第 2 个到第 4 个索引位置进行截取子串。
①函数式接口:
@FunctionalInterface
public interface I1 {
public String getValue(String str);
}
②测试:
public class Exer2 {
@Test
public void test1() {
I1 i1 = str -> str.toUpperCase();
String value = i1.getValue("abcd");
System.out.println(value);
}
@Test
public void test2() {
I1 i1 = str -> str.substring(2, 4);
String value = i1.getValue("hamburger");
System.out.println(value);
}
}
3. ①声明一个带两个泛型的函数式接口,泛型类型为 : T 为参 数,R 为返回值。 ②接口中声明对应抽象方法 ③在 LambdaTest 类中声明方法,使用接口作为参数,计算两个 long 型参数的和。 ④再计算两个 long 型参数的乘积
①函数式接口:
@FunctionalInterface
public interface I2<T,R> {
R calculate(T t1,T t2);
}
②测试:
public class Exer3 {
@Test
public void test1() {
//左返右参
I2<Long,Long> i2 = (t1,t2) -> Long.sum(t1, t2);
//类 :: 静态方法
I2<Long,Long> i = Long :: sum;
Long calculate = i.calculate(100L, 10L);
System.out.println(calculate);
}
@Test
public void test2() {
I2<Long,Long> i2 = (t1,t2) -> t1*t2;
Long calculate = i2.calculate(999L, 53253L);
System.out.println(calculate);
}
}