JDK1.8之内建函数式接口(方法引用的实现)

image.png
观察在JDK1.8之中提供的新的函数式接口包以及提供的四个函数式接口。

方法引用都需要定义一个函数式接口,可是不管如何操作,实际上有可能操作的接口只有四种,在JDK1.8提供了一个包java.util.function,提供有以下四个核心接口。

1.功能性接口(Function)

public interface Function<T,R>{public R apply(T t);}
此接口需要接收一个参数,并且返回一个处理结果

2.消费型接口(Consumer)

public interface Consumer<T>{public void accept(T t);}
此接口只是负责接收数据(引用数据是不需要返回的),并且不返回处理结果。

3.供给型接口(Supplier)

public interface Suppiler<T>{public T get();}
此接口不接收参数,但是返回结果。

4.断言型接口(Predicate)

public interface Predicate<T>{public boolean test(T t)}
进行判断操作使用

所有在JDK1.8之中,由于存在以上四个功能型接口,所以一般很少会由用户去定义新的函数是接口

范例:观察功能型接口——接收参数并且返回一个处理结果。
String类有一个方法:public boolean startsWith(String str)

package TestDemo;

import java.util.function.Function;

public class TestDemo{
    
    public static void main(String[] args) {
        
        Function<String,Boolean> fun="##hello"::startsWith;//方法引用赋给一个函数式接口

        System.out.println(fun.apply("##"));
    }
}

方法引用赋予一个函数式接口,最终的判断其实是"##hello".startsWith"##";这个语句。答案为true

范例:消费型接口

package TestDemo;

import java.util.function.Consumer;
import java.util.function.Function;

class MyDemo{
    public void print(String str){//此方法没有返回值,但是有参数
        System.out.println(str);
    }
}
public class TestDemo{
    
    public static void main(String[] args) {
        
        Consumer<String> cons=new MyDemo()::print;//方法引用赋给一个函数式接口

        cons.accept("Hello World!");
    }
}

范例:供给型接口(Supplier)
引用String类中的toUpperCase()方法
public String toUpperCase();

package TestDemo;

import java.util.function.Supplier;

public class TestDemo{
    
    public static void main(String[] args) {
        
        Supplier<String> sup="hello"::toUpperCase;//方法引用赋给一个函数式接口

        System.out.println(sup.get());
    }
    

}

结果"hello

范例:断言型接口(Predicate)
String类中有一个equalsIgnoreCase()方法

package TestDemo;

import java.util.function.Predicate;
import java.util.function.Supplier;

public class TestDemo{
    
    public static void main(String[] args) {
        
        Predicate<String> pre="hello"::equalsIgnoreCase;//方法引用赋给一个函数式接口

        System.out.println(pre.test("hello"));//不区分大小写判断是否相等
    }
}

答案为true

总结:

开发中所用到的函数式接口一般都为以上4种,所有讲的这一切都要为最后的数据流做准备。

关注公众号CodeInJava,Java学习图谱,数据结构与算法资料等各种资料都可以在后台获取。等你哦~
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容