小练习:
1、调用Collections.sort()方法,通过定制排序比较两个Employee(先按照年龄比较,年龄相同按照姓名比较)
@Test
void test01(){
List<Employee> emps = Arrays.asList(
new Employee(27,"刘富贵"),
new Employee(34,"刘生产"),
new Employee(23,"刘团结"),
new Employee(42,"刘向前"),
new Employee(19,"刘复兴")
);
Collections.sort(emps,(e1,e2) -> {
if(e1.getAge() == e2.getAge()){
return e1.getName().compareTo(e2.getName());
}
return Integer.compare(e1.getAge(),e2.getAge());
});
for (Employee emp : emps) {
System.out.println(emp);
}
}
2、
- 声明一个函数式接口,接口中声明抽象方法,public string getValue(String str)
- 声明一个类,类中编写方法使用接口作为参数,将一个字符串转换为大写,并作为方法的返回值
- 将一个字符串的第二和第四索引位置进行截取字符串
//函数式接口
@FunctionalInterface
public interface MyFunction {
//类型是确定的
public String getValue(String str);
}
//方法
public String stringHandler(String str, MyFunction mf){
return mf.getValue(str);
}
@Test
void test02(){
//将字符串转换为大写
String xiaowu = stringHandler("xiaowu", (str) -> str.toUpperCase());
//截取字符串
String subStr = stringHandler("xiaowu", (str) -> str.substring(2, 4));
System.out.println(xiaowu);
System.out.println(subStr);
}
3、声明一个接受泛型参数的函数式接口
@FunctionalInterface
public interface MyFunctionGenerictity<T,R> {
R getValue(T t1,T t2);
}
//接受两个Long型数据进行处理
public void operation(Long l1, Long l2, MyFunctionGenerictity<Long,Long> mg){
System.out.println(mg.getValue(l1,l2));
}
@Test
void test03(){
//2、声明一个接受泛型参数的函数式接口,
operation(2L,4L,(x,y) -> x * y);
}