lambda表达式与函数式接口(一)

本文介绍了Java中的函数式接口概念,强调了只有一个抽象方法的接口特性,并提到可以使用@FunctionalInterface注解。文章探讨了如何在函数式编程中结合lambda表达式,通过案例展示了函数式接口作为参数和返回值的应用。还详细讲解了JDK中的Supplier和Consumer接口,分别阐述了它们在生产数据和消费数据上的作用。
摘要由CSDN通过智能技术生成

概念
  • 有且只有一个抽象方法的接口,称之为函数式接口;该接口可以用@FunctionalInterface注解修饰,确保函数式接口定义的有效性。
/**
 * 函数式接口
 *
 * @author zhuhuix
 * @date 2020-07-12
 */
@FunctionalInterface
public interface FunctionInterface {
    // 有且只有一个抽象方法
    void function();


    // 接口有可以包括其他的方法(静态、默认、私有)
    static void print(){
        System.out.println("这是一个函数式接口中的静态方法");
    }
}
函数式编程
案例1:使用函数式接口做为参数
/**
 * 使用lambda表达式重写函数式接口中的抽象方法
 *
 * @author zhuhuix
 * @date 2020-07-12
 */
public class FunctionInterfaceLambda {
    static void callFunctionInterface(FunctionInterface functionInterface) {
    }

    public static void main(String[] args) {
        callFunctionInterface(() ->
                System.out.println("使用lambda表达式重写函数式接口中的抽象方法")
        );
    }
}
案例2:使用函数式接口做为返回值
/**
 * 函数式编程->人员类
 *
 * @author zhuhuix
 * @date 2020-07-11
 */
public class Person {
    //姓名
    private String name;
    //年龄
    private int age;

    public Person(){}

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

/**
 * 函数式编程->lambda有参数有返回值例子
 *
 * @author zhuhuix
 * @date 2020-07-11
 */
public class PersonArrays {

    public static void main(String[] args) {
        //创建Person数组
        Person[] personArray = {
                new Person("Mike", 20),
                new Person("Jack", 21),
                new Person("Rose", 19)
        };

        // 通过使用Comparator函数式接口进行年龄大小比较实现数组的排序
        Arrays.sort(personArray, Comparator.comparingInt(Person::getAge));

        //遍历Person数组
        for (int i = 0; i < personArray.length; i++) {
            System.out.println(personArray[i].toString());
        }

    }
}
  • Comparator.comparingInt 源码如下:
 /**
     * Accepts a function that extracts an {@code int} sort key from a type
     * {@code T}, and returns a {@code Comparator<T>} that compares by that
     * sort key.
     *
     * <p>The returned comparator is serializable if the specified function
     * is also serializable.
     *
     * @param  <T> the type of element to be compared
     * @param  keyExtractor the function used to extract the integer sort key
     * @return a comparator that compares by an extracted key
     * @see #comparing(Function)
     * @throws NullPointerException if the argument is null
     * @since 1.8
     */
    public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);
        return (Comparator<T> & Serializable)
            (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
    }
  • 程序输出如下:
    在这里插入图片描述
jdk中常用的函数式接口
Supplier接口
  • 生产型接口:指定接口的泛型是什么类型,那么接口中的get方法就会产生什么类型的数据。
@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
/**
 * 函数式编程--常用函数式接口
 *  * @author zhuhuix
 * @date 2020-07-11
 */
public class FunctionInterfaceDemo2 {
    // Supplier<T>
    public static String getString(Supplier<String> supplier) {
        return supplier.get();
    }

    public static void main(String[] args) {
        String string = getString(() -> "Supplier函数式接口");
        System.out.println(string);
    }
}
Consumer接口
  • 指定接口的泛型是什么类型,那么接口中的accept方法就会使用什么类型的数据。
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
 }
/**
 * 函数式编程--常用函数式接口
 *
 * @author zhuhuix
 * @date 2020-07-11
 */
public class FunctionInterfaceDemo2 {

    // Consume<T>
    public static void acceptString(String string ,Consumer<String> consumer){
        consumer.accept(string);
    }

    public static void main(String[] args) {
        acceptString("Consumer函数式接口",(String string1)-> System.out.println(string1));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧zhuhuix

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值