调用 Collection.sort() 方法, 通过定制排序比较两个 Employee(先按年龄比, 年龄相同按姓名比), 使用 Lambda 作为参数传递
- List<Employee> employees = Arrays.asList(
- new Employee("张三", 18 ,9999.99),
- new Employee("李四", 50, 5555.99),
- new Employee("王五", 50, 6666.66),
- new Employee("赵六", 16, 3333.33),
- new Employee("田七", 8, 7777.77)
- );
- @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());
- // 倒序排
- //return -Integer.compare(e1.getAge(), e2.getAge());
- }
- });
- for (Employee employee : employees){
- System.out.println(employee);
- }
- }
1. 声明函数式接口, 接口中声明抽象方法, public String getValue(String str);
2. 声明类 TestLambda, 类中编写方法使用接口作为参数, 将一个字符串转换为大写, 并作为方法的返回值
3. 再将一个字符串的第 2 个和第 4 个索引位置进行截取子串
- @FunctionalInterface
- public interface MyFunction {
- public String getValue(String str);
- }
- List<Employee> employees = Arrays.asList(
- new Employee("张三", 18 ,9999.99),
- new Employee("李四", 50, 5555.99),
- new Employee("王五", 50, 6666.66),
- new Employee("赵六", 16, 3333.33),
- new Employee("田七", 8, 7777.77)
- );
- // 需求: 用于处理字符串
- public String strHandler(String str, MyFunction mf){
- return mf.getValue(str);
- }
- @Test
- public void test2(){
- String trimStr = strHandler("abfdfdf", (str) -> str.toUpperCase());
- System.out.println(trimStr);
- String subStr = strHandler("abfdfdf", (str) -> str.substring(2, 4));
- System.out.println(subStr);
- }
1. 声明一个带两个泛型的函数式接口, 泛型类型为 < T, R> T 为参数, R 为返回值
2. 接口中声明对应抽象方法
3. 使用接口作为参数, 计算两个 long 类型参数的和
4. 再计算两个 long 型参数的乘积
- public interface MyFunction2<T, R> {
- public R getValue(T t1, T t2);
- }
- // 需求: 对于两个 Long 型数据进行处理
- public void op(Long l1, Long l2, MyFunction2<Long, Long> mf){
- System.out.println(mf.getValue(l1, l2));
- }
- @Test
- public void test3(){
- op(100L, 200L, (x, y) -> x + y);
- op(100L, 200L, (x, y) -> x * y);
- }
来源: http://www.bubuko.com/infodetail-3042603.html