深入探索-函数式接口的应用与个性化定制之道

举报
一颗小谷粒 发表于 2024/11/27 15:38:01 2024/11/27
【摘要】 在Java编程语言中,函数式接口是一个非常重要的概念,它简化了编程模型的复杂性,并促进了代码的可读性和重用性。函数式接口的核心特性是它们只有一个抽象方法,这使得它们可以被隐式地转换为lambda表达式或方法引用,从而轻松实现函数式编程范式。本文将深入探讨Java中函数式接口的概念、特点以及它们在实际编程中的应用,并介绍在大麦项目如何自定义函数式接口并介绍以及和设计模式之间的关系,帮助小伙伴更...

在Java编程语言中,函数式接口是一个非常重要的概念,它简化了编程模型的复杂性,并促进了代码的可读性和重用性。函数式接口的核心特性是它们只有一个抽象方法,这使得它们可以被隐式地转换为lambda表达式或方法引用,从而轻松实现函数式编程范式。

本文将深入探讨Java中函数式接口的概念、特点以及它们在实际编程中的应用,并介绍在大麦项目如何自定义函数式接口并介绍以及和设计模式之间的关系,帮助小伙伴更好地理解和运用这一强大的编程工具

四种函数式接口

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);

}

T类型作为入参类型,R类型作为出参类型

示例

public static void testFunction(){
    Function<Integer,String> function = str -> "转换后:"+str;
    System.out.println(function.apply(1));
}

执行结果

转换后:1


Consumer 接口(消费功能)

@FunctionalInterface
public interface Consumer<T> {

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

只有T类型的入参,没有出参,也就是要消费这个参数

示例

public static void testConsumer(){
    Consumer<String> consumer = str -> System.out.println("输出:"+str);
    consumer.accept("这是我");
}

执行结果

输出:这是我

Supplier 接口(提供功能)

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

只有T类型的出参

示例

public static void testSupplier(){
    Supplier<String> supplier = () -> "提供数据";
    System.out.println(supplier.get());
}

执行结果

提供数据

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);
  
}

T类型作为入参类型,boolean类型作为出参类型

示例

public static void testPredicate(){
    Predicate<Integer> predicate = (number) -> 1 == number;
    System.out.println("是否等于1:"+predicate.test(2));
}

执行结果

是否等于1:false


而stream流的所有操作都是围绕着这四种类型的函数式接口而展开的,这里举几个例子

public static void main(String[] args) {
    List<TestUser> testUserList = getTestUserList();
    List<String> testUserNameList = testUserList.stream().map(TestUser::getName).collect(Collectors.toList());
    testUserNameList.forEach((userName) -> System.out.println("用户名为:" + userName));
}

这里是将泛型为 TestUser 对象的集合先转换为stream流,然后通过map方法进一步转换为 TestUser中的name属性为元素的集合


【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。