03.JAVA8 中内置的四大核心函数式接口

JAVA8 中内置的四大核心函数式接口

消费性接口

Consumer< T >: 有一个参数,没有返回值

void accept(T t);

    @Test
    public void test(){
        happy(10000.0, x -> System.out.println("消费:"+x+"元"));
    }

    public void happy(Double menoy, Consumer<Double> consumer){
        consumer.accept(menoy);
    }

供给型接口

Supplier< T >:

T get();

    public List<Integer> getNumber(Integer num, Supplier<Integer> supplierp){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Integer integer= supplierp.get();
            list.add(integer);
        }
        return list;
    }

    @Test
    public void test(){
        List<Integer> numberList = getNumber(10, () -> (int)(Math.random() * 100));
        System.out.println(numberList);
    }

函数型接口

Function< T, R >:

R apply(T t);

    @Test
    public void test(){
        String s = strHandler("我是张三", x -> x.substring(2, 4));
        System.out.println(s);
    }

    public String strHandler(String str, Function<String, String> fun){
        return fun.apply(str);
    }

断言型接口

Predicate< T >:

boolean test(T t);

    //创建员工数据集demo
    List<Employee> employees = Arrays.asList(
            new Employee("五王",28,new BigDecimal(20000.00)),
            new Employee("李四",28,new BigDecimal(12000.00)),
            new Employee("张三",18,new BigDecimal(6000.00)),
            new Employee("赵六",38,new BigDecimal(17000.00)),
            new Employee("田七",48,new BigDecimal(3000.00))
    );    

	@Test
    public void test(){
        List<Employee> employees = filterList(employees, x -> x.getAge() >= 35);
        System.out.println(employees);
    }

    public List<Employee> filterList(List<Employee> employees, Predicate<Employee> pre){
        List<Employee> emps = new ArrayList<>();
        for (Employee employee:employees) {
           if (pre.test(employee)){
               emps.add(employee);
           }
        }
        return emps;
    }

猜你喜欢

转载自www.cnblogs.com/jwhu/p/12977011.html