练习:
- 调用Collections.sort()方法,通过制定排序比较两个Employee(先按年龄比,年龄相同按姓名比),使用Lambda作为参数传递;
- 声明函数式接口MyFunction,接口中声明抽象方法,public String getValue(String str) 声明类TestLambda,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值 再将一个字符串的第2个到第4个索引位置进行截取字符串;
- 声明一个带两个泛型的函数式接口,泛型类型为<T,R> T作为参数,R作为返回值。接口中声明对应抽象方法 在TestLambda类中声明方法,使用接口作为参数,计算两个long型参数的和 再计算两个long型参数的乘积
package lambda; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; public class TestLambda { List<Employee> employees = Arrays.asList( new Employee("张三", 25, 9000), new Employee("李四", 38, 10000), new Employee("王晓", 45, 12000), new Employee("李华", 28, 9500), new Employee("花花", 22, 8000) ); //1.调用Collections.sort()方法,通过制定排序比较两个Employee(先按年龄比,年龄相同按姓名比),使用Lambda作为参数传递 @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.声明函数式接口MyFunction,接口中声明抽象方法,public String getValue(String str) // 声明类TestLambda,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值 // 再将一个字符串的第2个到第4个索引位置进行截取字符串 @Test public void test2() { String str0 = operation2("\t\t\ttoday is a good day!\t\t\t", str -> str.trim()); //去除字符串首尾空格 String str1 = operation2(str0, str -> str.toUpperCase()); System.out.println(str1); String str2 = operation2(str1, str -> str1.substring(2, 5)); //截取,包头不包尾 System.out.println(str2); } public String operation2(String str, MyFunction myFunction) { return myFunction.getValue(str); } //3.声明一个带两个泛型的函数式接口,泛型类型为<T,R> T作为参数,R作为返回值 // 接口中声明对应抽象方法 // 在TestLambda类中声明方法,使用接口作为参数,计算两个long型参数的和 // 再计算两个long型参数的乘积 @Test public void test3() { // long num1 = operation3(100L, 100L, (x, y) -> x + y); // System.out.println(num1); // // long num2 = operation3(100L, 100L, (x, y) -> x * y); // System.out.println(num2); operation3(100L, 100L, (x, y) -> x + y); operation3(100L, 100L, (x, y) -> x * y); } // public long operation3(long m, long n, MyFunction2<Long, Long> myFunction2) { // return myFunction2.getValue(m, n); // } public void operation3(long m, long n, MyFunction2<Long, Long> myFunction2) { System.out.println(myFunction2.getValue(m,n)); } }
相关函数声明详见:https://blog.csdn.net/qq_38358499/article/details/104636487
Java8新特性之Lambda表达式(五)
最新推荐文章于 2022-03-24 16:24:09 发布