java8新特性

2022-06-29  本文已影响0人  liangxifeng833

常用内置函数接口, 接口只包含一个抽象方法

  1. 消费型接口:Consumer<T> - void accept(T t)
    接受参数,但是无返回值
class ConsumerDemo {
  public static void bath(int money, Consumer<Integer> spendMoney) {
      spendMoney.accept(money);
  }
  public static void main(String[] args) {
      // 我搞了一个桃村,话费了 = 100
      bath(100,x -> System.out.println("我搞了一个套餐,话费了=" + x));
  }
}
  1. 供给型接口:Supplier<T> - T get()
    Supplier 接口翻译过来就是提供者
    该接口对应的方法类型为 不接受参数,但是提供一个返回值
    使用get()方法获得这个返回值
  Supplier<String> getInstance = () -> "HelloWorld!";
  System.out.println(getInstance.get());
  // 控偶值台输出 HelloWorld
  1. 函数型接口:Function<T,R> - R apply(T t)
    它接受一个T类型的参数,返回一个R类型的返回值;
    通过调用apply方法执行内容
public class FunctionApiExample {
    /**
    下面这个方法接受一个int类型参数a,返回a+1,符合接受一个参数,返回一个值
    所以呢这个方法就符合Function接口的定义,那要怎么用呢,继续看例子
    */
    public static int addOne(int a) {
        return a+1;
    }
    /**
    该方法第二个参数接受一个function类型的行为,然后调用apply,对a执行这段行为
    */
    public static int oper(int a, Function<Integer,Integer> action){
        return action.apply(a);
    }

    /* 下面调用这个oper方法,将addOne方法作为参数传递 */
    public static void main(String[] args){
        //Function 单独使用
        Function<Integer,Integer> f = s->(s*2);
        Integer i = f.apply(2);
        System.out.println(i); //输出4


        int x = 1;
        int y = oper(1,m -> addOne(m));//这里可以换成方法引用的写法 int y = oper(x,Operation::addOne(x))
        System.out.printf("x= %d, y = %d", x, y); // 打印结果 x=1, y=2

        /* 当然你也可以使用lambda表达式来表示这段行为,只要保证一个参数,一个返回值就能匹配 */
        y = oper(x, p -> p + 3 ); // y = 4
        System.out.println("y="+y);
        y = oper(x, p -> p * 3 ); // y = 3
        System.out.println("y="+y);
    }
}
  1. 断言型接口:Predicate<T> - boolean (T t)
    中文中的‘是 不是 中文语法的谓语
    该接口对应的方法为接收一个T类型参数,返回一个Boolean类型值;
    多用于判断与过滤
    使用test()方法执行这段行为
       public static void main(String[] args) {
            Predicate<Integer> predOdd = integer -> integer % 2 == 1;
            System.out.println(predOdd.test(5));
            //控制台输出 true
        }
    

方法引用

Optional解决空指针异常简单方法

方法引用

Stream 教程

上一篇下一篇

猜你喜欢

热点阅读