java8 Lambda表达式和四大函数式接口

Lambda表达式可以简化代码的书写,可以用几行代码实现复杂的功能。当然也让代码看着高大上一点。

package com.example.java8.java8test;

import com.example.java8.mapper.Employee;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * 一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
 *                        箭头操作符将 Lambda 表达式拆分成两部分:
 *
 * 左侧:Lambda 表达式的参数列表
 * 右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体
 *
 * 语法格式一:无参数,无返回值
 *        () -> System.out.println("Hello Lambda!");
 *
 * 语法格式二:有一个参数,并且无返回值
 *        (x) -> System.out.println(x)
 *
 * 语法格式三:若只有一个参数,小括号可以省略不写
 *        x -> System.out.println(x)
 *
 * 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
 *    Comparator<Integer> com = (x, y) -> {
 *       System.out.println("函数式接口");
 *       return Integer.compare(x, y);
 *    };
 *
 * 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
 *        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
 *
 * 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
 *        (Integer x, Integer y) -> Integer.compare(x, y);
 *
 *
 * 二、Lambda 表达式需要“函数式接口”的支持
 * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
 *            可以检查是否是函数式接口
 */
public class LambdaTest {

    /**
     * 当前公司的员工信息
     */
    private  List<Employee> employees = Arrays.asList(
            new Employee(1,"sun",25,5000.0, Employee.Status.BUSY),
            new Employee(3,"tina",22,4500.0, Employee.Status.FREE),
            new Employee(4,"jack",66,9900.0, Employee.Status.VOCATION),
            new Employee(5,"peter",77,4509.99, Employee.Status.BUSY),
            new Employee(6,"lose",10,888.8, Employee.Status.BUSY),
            new Employee(11,"lose",10,888.8, Employee.Status.BUSY),
            new Employee(12,"lose",10,888.8, Employee.Status.BUSY),
            new Employee(13,"lose",10,888.8, Employee.Status.BUSY),
            new Employee(7,"rise",39,682.2, Employee.Status.VOCATION),
            new Employee(8,"dex",56,15000.0, Employee.Status.VOCATION),
            new Employee(9,"great",12,3000.98, Employee.Status.FREE),
            new Employee(10,"lady",33,26859.2, Employee.Status.FREE)
    );

    /**
     * 个人感觉Lambda表达式就是匿名内部类的简化
     */
    @Test
    public void test1() {
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        };
        Comparator<Integer> comparator1 = (x, y) -> x - y;

        List<Integer> integers = Arrays.asList(1, 23, 4, 13, 50, 78, 6, 90);
        integers.sort(comparator);
        for (Integer i : integers){
            System.out.println(i);
        }
        System.out.println("<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>");
        List<Integer> integers1 = Arrays.asList(1, 23, 4, 13, 50, 78, 6, 90);
        integers1.sort(comparator1);
        for (Integer i : integers1){
            System.out.println(i);
        }
    }

    /**
     * 根据不同的信息,查询出所需要的员工信息
     *
     * Predicate 断言型接口
     * 确定类型为T的对象是否满足某约束,并返回boolean值,包含方法:boolean test(T t);
     */
    public List<Employee> filterEmployee(List<Employee> emps, Predicate<Employee> mp){
        List<Employee> list = new ArrayList<>();

        for (Employee employee : emps) {
            if(mp.test(employee)){
                list.add(employee);
            }
        }
        return list;
    }

    /**
     * Consumner<T> : 消费型接口
     *用途:对类型为T的对象应用操作,包含方法:void accept(T t);
     */
    public void displayEmployss(List emps, Consumer consumer){
        for (Object e :emps){
            consumer.accept(e);
        }
    }

    /**
     * Supplier<T> :供给型接口
     *用途:返回类型为T的对象,包含方法:T get();
     *
     */
    public List supply(Integer num, Supplier supplier){
        List list = new ArrayList<>();
        for (int i=0;i<num;i++){
            list.add(supplier.get());
        }
        return list;
    }

    public List<Object> functionEmployee(List<Employee> employees, Function<Employee,Object> function){
       List<Object> list = new ArrayList<>();
        for (Employee employee:employees){
            list.add(function.apply(employee));
        }
        return list;
    }
    /**
     * 测试 ----filterEmployee
     */
    @Test
    public void test2(){
        System.out.println("选出工资5K以上的员工信息");
        List<Employee> salary =filterEmployee(employees,employee -> employee.getSalary() > 5000);
        for (Employee e : salary){
            System.out.println(e.toString());
        }
        System.out.println("选出姓名中含有 字母 e 的");
        List<Employee> names = filterEmployee(employees,employee -> employee.getName().contains("e"));
        displayEmployss(names,System.out::println);
        System.out.println("随机去除10个1000以内的整数");
        List supply = supply(10, () -> (int)(Math.random()*1000));
       displayEmployss(supply,System.out::println);
        System.out.println("查询所有人工资");
        List<Object> objects = functionEmployee(employees, x -> x.getSalary());
        displayEmployss(objects,System.out::println);
    }

}

函数式接口参考连接   https://blog.csdn.net/an1090239782/article/details/78583382

--------------------------------------------------------------------------------------------------

实体类

package com.example.java8.mapper;
/**
 * @Author peter
 * 模拟实体类,公司人员信息
 */
public class Employee {
    /**
     * 人员id
     */
    private int id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private int age;
    /**
     * 工资收入
     */
    private Double salary;
    /**
     * 状态
     */
    private Status status;

    public Employee(int id, String name, int age, Double salary, Status status) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.status = status;
    }

    public Employee() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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 Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Employee employee = (Employee) o;

        if (age != employee.age) return false;
        if (!name.equals(employee.name)) return false;
        if (!salary.equals(employee.salary)) return false;
        return status == employee.status;
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + age;
        result = 31 * result + salary.hashCode();
        result = 31 * result + status.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                ", status=" + status +
                '}';
    }

    public enum Status {
        FREE, BUSY, VOCATION;
    }
}

猜你喜欢

转载自blog.csdn.net/Peter_S/article/details/88027423