376-383 常用函数式接口

376 常用函数式接口:Supplier

预定义

Java8在java.util.function包下预定义了大量的函数式接口,这里重点学习4个:

Supplier

Consumer

Predicate

Function

【Supplier】

被称为生产型接口,主要用于提供结果。

包含1个get方法,返回<>泛型。该方法不需要参数,它会按某种逻辑(由LambDa实现)返回一个<>数据。如果指定了接口泛型,get方法就会返回什么类型的数据。

【练习需求】

定义一个String getString(Supplier<String> sub)方法,返回数据

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

package e376aso;

import java.util.function.Supplier;

public class Demo376 {

    public static void main(String[] args) {

        System.out.println(getString(() -> "mole"));

        System.out.println(getInteger(() -> 3));

//        why nothing in the () of parameter

    }

    private static String getString(Supplier<String> su) {

        return su.get();

    }

    private static int getInteger(Supplier<Integer> suu) {

//        返回值写int是可以的,这里可以自动拆箱装箱

        return suu.get();

    }

}

//what the meaning of the two method? why i need them?

//mole

//3

377 Supplier练习获取最大值

378 常用函数式接口Consumer

Consumer<T>被称为消费性接口,它消费的数据的类型由泛型指定

interface Consumer<T>表示接受单个输入参数且 不返回结果的操作。与大多数其他功能接口不同,Consumer预期通过副作用进行操作。

包含2个方法:

(1个抽象方法,1个默认方法)

void accept(T t),对给定的参数执行此操作

default Consumer<T> andThen(Consumer<? super T> after),返回一个组成的Consumer,依次执行此操作,然后执行after操作

【练习需求】

定义一个方法,消费1个字符串数据

定义一个方法,消费2个字符串数据

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

package e376aso;

import java.util.function.Consumer;

public class Demo378Consumer {

    public static void main(String[] args) {

        operateString("morning", ss -> System.out.println(ss));

        operateString("abc", ss -> System.out.pr

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值