Java8的lambda表达式学习记录—lambda练习题
1)调用 Collection.sort() 方法,通过定制排序比较两个 Emp (先按年龄比较,年龄相同再按姓名比),使用 Lambda 作为参数传递.
2.1)声明函数式接口,接口中声明抽象方法,public String getValue(String str);
2.2)声明类 TestLambda,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值.
2.3)再将一个字符串的第2个和第4个索引位置进行截取子串.
3.1)声明一个带两个泛型的函数式接口,泛型类型为<T, R> T为参数,R为返回值.
3.2)接口中声明对应的抽象方法.
3.3)在 TestLambda 类中声明方法,使用接口作为参数,计算两个 long 型参数的和.
3.4)在计算两个 long 型参数的乘积.
问题一:
public class Emp {
private String name;
private int age;
private double salary;
}
public class test {
List<Emp> emps = Arrays.asList(
new Emp("张三", 18, 9999.99),
new Emp("李四", 20, 7777.77),
new Emp("王五", 36, 5555.55),
new Emp("赵六", 50, 3333.33),
new Emp("田七", 10, 2222.22)
);
//调用 Collection.sort() 方法,通过定制排序比较两个 Emp (先按年龄比较,年龄相同再按姓名比),使用 Lambda 作为参数传递
@Test
public void test1(){
Collections.sort(emps, (x, y) -> {//lambda表达式中有多个语句时,需要用大括号括起来
if (x.getAge() == y.getAge()){
return x.getName().compareTo(y.getName());//调用 String.compareTo() 方法
}else {
return Integer.compare(x.getAge(), y.getAge());
}
});
for (Emp emp : emps) {
System.out.println(emp);
}
}
}
问题二:
//声明函数式接口,接口中声明抽象方法,public String getValue(String str);
@FunctionalInterface
public interface LambdaValue {
String getValue(String str);
}
//声明类 TestLambda,类中编写方法使用接口作为参数
public class TestLambda {
public String go(String s, LambdaValue lv){
return lv.getValue(s);
}
@Test
public void test1(){//将一个字符串转换成大写,并作为方法的返回值.
String str = go("abcdefg", (e) -> e.toUpperCase());
System.out.println(str);
}
@Test
public void test2(){//将一个字符串的第2个和第4个索引位置进行截取子串
String str = go("abcdefg", (e) -> e.substring(2, 4));
System.out.println(str);
}
}
问题三:
//声明一个带两个泛型的函数式接口,泛型类型为<T, R> T为参数,R为返回值
@FunctionalInterface
public interface FunctionLambda<T, R> {
R getValue(T t, T t2);
}
public class TestLambda {
//在 TestLambda 类中声明方法,使用接口作为参数
public Long go2(Long l1, Long l2, FunctionLambda<Long, Long> fl){
return fl.getValue(l1, l2);
}
@Test
public void test3(){//计算两个 long 型参数的和
Long l = go2(99999999999L, 11111111111L, (x, y) -> x + y);
System.out.println(l);
}
@Test
public void test4(){//计算两个 long 型参数的乘积
Long l = go2(99999999999L, 11111111111L, (x, y) -> x*y);
System.out.println(l);
}
}