1.创建实体 package com.it; public class Employee { private String name; private int age; private double salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public Employee() { super(); } public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}'; } }
编写测试类
package com.it; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * 一 lambda 表达式的基础语法, java8引入一个新的操作符"->" 该操作符称为箭头 * 操作符或lambda操作 * */ public class testLamdba3 { List<Employee> emps = Arrays.asList( new Employee("张三",18,9999.99) , new Employee("李四",38,959.99) , new Employee("王五",50,99.99) , new Employee("田七",8,919.99) ); /** * -Integer.compare(e1.getAge(),e2.getAge()); 从小到大 * Integer.compare(e1.getAge(),e2.getAge()); 从大到小 * */ @Test public void test1(){ Collections.sort(emps,(e1, e2)->{ if(e1.getAge() == e2.getAge()) { return e1.getName().compareTo(e2.getName()); }else{ return -Integer.compare(e1.getAge(),e2.getAge()); } }); for (Employee emp : emps){ System.out.println(emp); } }
//用于处理字符串 //substring 拆分字符串 //str.toUpperCase转换成大写 @Test public void tes2(){ String trimStr = strHandler("\t\t\t 我的美丽家乡河南 ", (str) -> str.trim()); System.out.println(trimStr); String upper= strHandler("ssage",(str) -> str.toUpperCase()); System.out.println(upper); String newStr=strHandler("我的美丽家乡河南" , (str) -> str.substring(2,5)); System.out.println(newStr); } public String strHandler(String str, MyFunction mf){ return mf.getValue(str); } @Test public void test3(){ op(100L,200L,(x,y) -> x + y); op(100L,200L,(x,y) -> x*y); } //需求: 对于两个Long 类型进行处理 public void op(Long l1,Long l2,MyFunction2<Long,Long> mf){ System.out.println(mf.getValue(l1,l2)); } }