Java8之函数式接口及常用函数式接口讲解

目录
  • 函数式接口
    • 1.概念
    • 2.@FunctionalInterface
    • 3.函数式接口使用方式
  • 常用函数式接口
    • 1.JDK提供的函数式接口举栗
    • 2.Supplier
    • 3.Consumer
    • 4.Predicate
    • 5.Function
    • 6.常用函数式接口相关扩展接口

函数式接口

1.概念

函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。

函数式接口可以被隐式转换为 lambda 表达式。

Lambda 表达式和方法引用(实际上也可认为是Lambda表达式)上。

2.@FunctionalInterface

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

我们常用的Runnable接口就是个典型的函数式接口,我们可以看到它有且仅有一个抽象方法run。并且可以看到一个注解@FunctionalInterface,这个注解的作用是强制你的接口只有一个抽象方法。

如果有多个话直接会报错,如图:

idea错误提示:

编译时错误提示:

这里当你写了第二个方法时,编译就无法通过,idea甚至在编码阶段就行了提示。

3.函数式接口使用方式

我们直接上代码,首先定义一个函数式接口

@FunctionalInterface
public interface SingleAbstraMethodInterface {
    public abstract void singleMethod();
}

我们定一个test类,封装一个方法,将SingleAbstraMethodInterface当做参数传入方法,并打印一句话

public class Test {
    public void testMethod(SingleAbstraMethodInterface single){
        System.out.println("即将执行函数式接口外部定义方法");
        single.singleMethod();
    }
    public static void main(String[] args) {
        Test test = new Test();
        test.testMethod(new SingleAbstraMethodInterface() {
            @Override
            public void singleMethod() {
                System.out.println("执行函数式接口定义方法");
            }
        });
    }
}

执行结果:

即将执行函数式接口外部定义方法
执行函数式接口定义方法

是不是和我们预期结果一样。这个过程是不是有的同学已经发现,怎么这么像jdk里面的一些接口的使用,比如常用的Runnable接口。

我们来看看代码。

public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("run方法执行了");
            }
        }).start();
}

再看下Runnable接口源码,是不是一样

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

这时,有的同学会说,我用Runnable接口可不是这么用的,我的写法比你优雅,我是这么写的。

没错函数式接口,函数式编程,我们可以使用lambda表达式的写法,可以让代码更优雅,具体可以参照我的前一篇帖子。Java8之Lambda表达式

public static void main(String[] args) {
        new Thread(()-> {
           System.out.println("run方法执行了");
        }).start();
}

常用函数式接口

1.JDK提供的函数式接口举栗

java.lang.Runnable,
java.awt.event.ActionListener,
java.util.Comparator,
java.util.concurrent.Callable

java.util.function包下的接口,如Consumer、Predicate、Supplier等

其实,jdk中给我们提供了很多的函数式接口,我们平时都会用到,只不过大家没有注意到而已,这里我结合实际代码讲解几个常用的函数式接口。想想大家平时常常用到stream流的各种方法来处理list。我看去stream类中看一下它提供的方法。可以看到有几个出镜率较高的函数式接口

  • Supplier
  • Comsumer
  • Predicate
  • Function

2.Supplier

@FunctionalInterface
public interface Supplier<T> {
    /**
     * Gets a result.
     * @return a result
     */
    T get();
}

Supplier接口的get方法没有入参,返回一个泛型T对象。

我们来看几个使用 的实例。

先写一个实验对象girl,我们定义一个方法,创建对象,我们使用lambda的方式来调用并创建对象。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Girl {

    private String name;

    private Double size;

    private Double price;

    public static Girl create(final Supplier<Girl> supplier) {
        return supplier.get();
    }

    public static void main(String[] args) {
    	//创建对象
        Girl girl1 = Girl.create(Girl::new);
        Girl girl2 = Girl.create(()-> new Girl("lily",33d,1700d));
        Girl girl = null;
        //orElseGet
        Girl girl3 = Optional.ofNullable(girl).orElseGet(Girl::new);
    }

}

需要注意的是,我没每调用一次get方法,都会重新创建一个对象

orElseGet方法入参同样也是Supplier,这里对girl实例进行判断,通过Supplier实现了懒加载,也就是说只有当判断girl为null时,才会通过orElseGet方法创建新的对象并且返回。不得不说这个设计是非常的巧妙。

3.Consumer

源码如下:

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

可以看到accept方法接受一个对象,没有返回值。

那么我们来实战,首先使用Lambda表达式声明一个Supplier的实例,它是用来创建Girl实例;再使用Lambda表达式声明一个Consumer的实例,它是用于打印出Girl实例的toString信息;最后Consumer消费了Supplier生产的Girl。

我们常用的forEach方法入参也是Consumer。

使用代码如下:

	Supplier<Girl> supplier = ()-> new Girl("lucy",33d,1700d);
	Consumer<Girl> consumer = (Girl g)->{
	   System.out.println(g.toString());
	};
	consumer.accept(supplier.get());
	ArrayList<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
    list.forEach(System.out::println);

4.Predicate

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
}

可以看到test方法接受一个对象,返回boolean类型,这个函数显然是用来判断真假。

那么我们用这个接口来构造一个判断女孩子条件的示例,还有我们常用的stream流中,filter的入参也是Predicate,代码如下:

		Supplier<Girl> supplier = ()-> new Girl("lucy",33d,1700d);
        Predicate<Girl> girl36d = (Girl g)-> Objects.equals(g.getSize(),36d);
        Predicate<Girl> girl33d = (Girl g)-> Objects.equals(g.getSize(),33d);
        boolean test33 = girl33d.test(supplier.get());
        boolean test36 = girl36d.test(supplier.get());
        System.out.println(supplier.get().getName() +"是否为[36d] :"+test36);
        System.out.println(supplier.get().getName() +"是否为[33d] :"+test33);

结果为:

lucy是否为[36d] :false
lucy是否为[33d] :true

		ArrayList<Girl> list = Lists.newArrayList();
        list.add(new Girl("露西", 33d, 2000d));
        list.add(new Girl("格蕾丝", 36d, 3000d));
        list.add(new Girl("安娜", 28d, 1500d));
        list.add(new Girl("克瑞斯", 31d, 1800d));
        Predicate<Girl> greaterThan30d = (Girl g)-> g.getSize()>=30d;
        list.stream().filter(greaterThan30d).forEach(System.out::println);

结果如下:

Girl(name=露西, size=33.0, price=2000.0)
Girl(name=格蕾丝, size=36.0, price=3000.0)
Girl(name=克瑞斯, size=31.0, price=1800.0)

5.Function

@FunctionalInterface
public interface Function<T, R> {
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
}

这个看到apply接口接收一个泛型为T的入参,返回一个泛型为R的返回值,所以它的用途和Supplier还是略有区别。还是一样我们举个栗子用代码来说明:

Supplier<Girl> supplier = ()-> new Girl("lucy",33d,1700d);
 Function<Girl,String> girlMark = (Girl g)-> g.getName()+"的尺寸是"+g.getSize()+",每次能赚"+g.getPrice()+"。";
 System.out.println(girlMark.apply(supplier.get()));

我们可以看到funtion接口接收Girl对象实例,对girl的成员变量进行拼接,返回girl的描述信息。其基本用法就是如此。

lucy的尺寸是33.0,每次能赚1700.0。

6.常用函数式接口相关扩展接口

这里我列举一些Supplier相关接口

a.Supplier相关拓展接口

接口名称 方法名称 方法签名
Supplier get () -> T
BooleanSupplier getAsBoolean () -> boolean
DoubleSupplier getAsDouble () -> double
IntSupplier getAsInt () -> int
LongSupplier getAsLong () -> long

b.Comsumer相关拓展接口

接口名称 方法名称 方法签名
Consumer accept (T) -> void
DoubleConsumer accept (double) -> void
IntConsumer accept (int) -> void
LongConsumer accept (long) -> void
ObjDoubleConsumer accept (T, double) -> vo
ObjIntConsumer accept (T, int) -> void
ObjLongConsumer accept (T, long) -> void

c.Predicate相关拓展接口

接口名称 方法名称 方法签名
Predicate test (T) -> boolean
BiPredicate test (T, U) -> boolean
DoublePredicate test (double) -> bool
IntPredicate test (int) -> boolean
LongPredicate test (long) -> boolean

d.Function相关的接口

接口名称 方法名称 方法签名
Function apply (T) -> R
BiFunction apply (T, U) -> R
DoubleFunction apply (double) -> R
DoubleToIntFunction applyAsInt (double) -> int
DoubleToLongFunction applyAsLong (double) -> long
IntFunction apply (int) -> R
IntToDoubleFunction applyAsDouble (int) -> double
IntToLongFunction applyAsLong (int) -> long
LongFunction apply (long) -> R
LongToDoubleFunction applyAsDouble (long) -> double
LongToIntFunction applyAsInt (long) -> int
ToDoubleFunction applyAsDouble (T) -> double
ToDoubleBiFunction applyAsDouble (T, U) -> double
ToIntFunction applyAsInt (T) -> int
ToIntBiFunction applyAsInt (T, U) -> int
ToLongFunction applyAsLong (T) -> long
ToLongBiFunction applyAsLong (T, U) -> long

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Java特性 Lambda 表达式和函数式接口

    目录 Java Lambda表达式 起源&概念 语法 简单例子 Lambda简化Runnable例子 代码分析 自定义接口实现lambda 函数式接口 概念 备注 格式 @FunctionalInterface注解 自定义函数式接口 Java Lambda表达式 为方便使用Java函数式接口,一定要搞清楚Java的Lambda表达式怎么书写.同时Java的Lambda不是那么通俗易懂,所以一定得学明白,不然其实后面涉及到Lambda的代码部分会变得晦涩难懂.而且掌握Lambda表达式可以让你写出

  • Java Lambda表达式常用的函数式接口

    失去人性,失去很多:失去兽性,失去一切.——<三体> 在Java8支持Lambda表达式以后,为了满足Lambda表达式的一些典型使用场景,JDK为我们提供了大量常用的函数式接口.它们主要在 java.util.function 包中,下面简单介绍几个其中的接口及其使用示例. Supplier接口 Supplier接口是对象实例的提供者,定义了一个名叫get的抽象方法,它没有任何入参,并返回一个泛型T对象,具体源码如下: package java.util.function; @Functio

  • java之函数式接口解读

    目录 一.函数式接口 @FunctionalInterface注解 性能浪费的日志案例 使用Lambda优化日志案例 使用Lambda作为参数和返回值 二.常用函数式接口 Supplier接口 Consumer接口 Predicate接口 Function接口 总结 一.函数式接口 概念 函数式接口在Java中是指:有且仅有一个抽象方法的接口. 当然接口中可以包含其他的方法(默认,静态,私有) 函数式接口,即适用于函数式编程场景的接口.而Java中的函数式编程体现就是Lambda,所以函数式接口

  • java理论基础函数式接口特点示例解析

    目录 一.函数式接口是什么? 所谓的函数式接口,实际上就是接口里面只能有一个抽象方法的接口.我们上一节用到的Comparator接口就是一个典型的函数式接口,它只有一个抽象方法compare. 只有一个抽象方法?那上图中的equals方法不是也没有函数体么?不急,和我一起往下看! 二.函数式接口的特点 接口有且仅有一个抽象方法,如上图的抽象方法compare允许定义静态非抽象方法 允许定义默认defalut非抽象方法(default方法也是java8才有的,见下文)允许java.lang.Obj

  • Java8之函数式接口及常用函数式接口讲解

    目录 函数式接口 1.概念 2.@FunctionalInterface 3.函数式接口使用方式 常用函数式接口 1.JDK提供的函数式接口举栗 2.Supplier 3.Consumer 4.Predicate 5.Function 6.常用函数式接口相关扩展接口 函数式接口 1.概念 函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口. 函数式接口可以被隐式转换为 lambda 表达式. Lambda 表达式和方法引用(实际上也

  • 浅析Java8新特性Lambda表达式和函数式接口

    什么是Lambda表达式,java8为什么使用Lambda表达式? "Lambda 表达式"(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数.我们可以把 Lambda表达式理解为是 一段可以传递的代码.最直观的是使用Lambda表达式之后不用再写大量的匿名内部类,简化代码,提高了代码的可读性. // 启动一个线程,不使用Lambda

  • Java8简单了解Lambda表达式与函数式接口

    Java8被称作Java史上变化最大的一个版本.其中包含很多重要的新特性,最核心的就是增加了Lambda表达式和StreamAPI.这两者也可以结合在一起使用.首先来看下什么是Lambda表达式. 使用Lambda表达式不仅让代码变的简单.而且可读.最重要的是代码量也随之减少很多.然而,在某种程度上,这些功能在Scala等这些JVM语言里已经被广泛使用. 并不奇怪,Scala社区是难以置信的,因为许多Java 8里的内容看起来就像是从Scala里搬过来的.在某种程度上,Java 8的语法要比Sc

  • Java常用函数式接口总结

    四大函数式接口 新时代的程序员:lambda 表达式,链式编程,函数式接口,Stream 流式计算 函数式接口: 只有一个方法的接口 @FunctionalInterface public interface Runnable { public abstract void run(); } //超级多FunctionalInterface //简化编程模型,在新版本的框架底层大量应用! //foreach(消费者类型的函数式接口) 代码测试: Function 函数式接口 package com

  • PHP封装curl的调用接口及常用函数详解

    如下所示: <?php /** * @desc 封装curl的调用接口,post的请求方式 */ function doCurlPostRequest($url, $requestString, $timeout = 5) { if($url == "" || $requestString == "" || $timeout <= 0){ return false; } $con = curl_init((string)$url); curl_setop

  • Java调用第三方http接口的常用方式总结

    目录 1.概述 在Java项目中调用第三方接口的常用方式有 2.Java调用第三方http接口的方式 2.1 通过JDK网络类Java.net.HttpURLConnection 2.2 通过apache common封装好的HttpClient 2.3 通过Apache封装好的CloseableHttpClient 2.4 通过OkHttp 2.5 通过Spring的RestTemplate 2.6通过hutool的HttpUtil 3.总结 1.概述 在实际开发过程中,我们经常需要调用对方提

  • C++List容器常用函数接口刨析

    目录 一.基本结构 二.list的迭代器的构造 三.迭代器的实现 四.insert,erase 五.push_back,push_front,pop_back,pop_front 六.构造函数与赋值重载 七.析构与清空 一.基本结构 由源代码可知,list容器是有一个带头双向循环链表实现,所以我们模拟实现也需要实现一个带头双向循环链表的数据结构. template<class T> struct list_node { list_node<T>* _next; list_node&

  • C++Vector容器常用函数接口详解

    目录 一.基础框架 二.迭代器实现 三.size capacity resize reserve 四.insert,erase 五.pop_back,push_back 六.operator[] 七.构造函数 析构函数 赋值重载 一.基础框架 template<class T> class vector { public: typedef T* iterator; typedef const T* const_iterator; private: iterator _start;//指向第一个

  • Python函数式编程指南:对生成器全面讲解

    生成器是迭代器,同时也并不仅仅是迭代器,不过迭代器之外的用途实在是不多,所以我们可以大声地说:生成器提供了非常方便的自定义迭代器的途径. 这是函数式编程指南的最后一篇,似乎拖了一个星期才写好,嗯-- 1. 生成器(generator) 1.1. 生成器简介 首先请确信,生成器就是一种迭代器.生成器拥有next方法并且行为与迭代器完全相同,这意味着生成器也可以用于Python的for循环中.另外,对于生成器的特殊语法支持使得编写一个生成器比自定义一个常规的迭代器要简单不少,所以生成器也是最常用到的

  • java实现一个接口调取另一个接口(接口一调取接口二)

    目录 java一个接口调取另一个接口 工具类 springboot中使用(接口一) 接口二 接口的调用与调用别人的接口 别人调用我们的接口,与controller方法开发类似 我们调用别人的接口 java一个接口调取另一个接口 工具类 package com.utils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Print

随机推荐