欢迎访问宙启技术站
智能推送

Java函数-函数式接口

发布时间:2023-05-28 17:05:18

Java语言中,函数也是一等公民,Java中的函数也能像其他数据类型一样实现存储、传递和返回等功能。在Java中,函数式接口是指只有一个抽象方法的接口。

为什么需要函数式接口?在Java中,函数式接口是一个很重要的概念,它的提出主要是为了支持函数式编程的特性。可以说,函数式接口是支持Java 8 的Lambda表达式的基础,它提供了一种更为便捷的编程方式。

函数式接口最重要的概念是Lambda表达式。使用Lambda表达式可以很方便地编写函数式接口的实现。

下面是一个简单的例子:

interface MyInterface{
    void foo();
}

public class MyTest{
    public static void main(String[] args){
        MyInterface myInterface = ()->System.out.println("foo");
        myInterface.foo();
    }
}

在这个例子中,我们定义了一个函数式接口MyInterface,它只有一个抽象方法foo。我们使用Lambda表达式实现foo方法,并将该实现赋给myInterface对象。当调用myInterface的foo方法时,输出“foo”字符串。

下面,我们介绍几种常见的函数式接口。

1. Consumer

Consumer接口表示接受一个参数并且没有返回值的操作。例如,输出一个字符串:

Consumer<String> consumer = System.out::println;
consumer.accept("hello world");

这里,我们通过方法引用将System.out.println方法赋给consumer,然后调用consumer的accept方法,输出“hello world”字符串。

Consumer接口还可以串联,使用andThen方法:

Consumer<String> consumer1 = System.out::println;
Consumer<String> consumer2 = s -> System.out.println(s.length());
consumer1.andThen(consumer2).accept("hello world");

这里,我们先调用consumer1的accept方法输出“hello world”字符串,然后调用consumer2的accept方法输出字符串长度。

2. Function

Function接口表示接受一个参数并产生一个结果的操作。例如,将字符串转换为大写:

Function<String, String> function = String::toUpperCase;
String result = function.apply("hello world");
System.out.println(result);

这里,我们通过方法引用将String.toUpperCase方法赋给function,调用function的apply方法将“hello world”转换为大写字符串并输出。

Function接口还可以串联,使用andThen方法:

Function<String, Integer> function1 = String::length;
Function<Integer, String> function2 = i -> "length is " + i;
String result = function1.andThen(function2).apply("hello world");
System.out.println(result);

这里,我们先调用function1的apply方法得到“hello world”的长度,然后调用function2的apply方法得到字符串“length is 11”并输出。

3. Predicate

Predicate接口表示接受一个参数并返回一个Boolean值的操作。例如,判断一个字符串是否为空:

Predicate<String> predicate = String::isEmpty;
boolean result = predicate.test("");
System.out.println(result);

这里,我们通过方法引用将String.isEmpty方法赋给predicate,调用predicate的test方法判断一个字符串是否为空,并输出结果。

Predicate接口还可以串联,使用and、or和negate方法:

Predicate<String> predicate1 = s -> s.startsWith("h");
Predicate<String> predicate2= s -> s.length() > 5;
boolean result = predicate1.and(predicate2).test("hello world");
System.out.println(result);

这里,我们先判断字符串是否以“h”开头,再判断字符串长度是否大于5,在调用and方法对两个结果进行逻辑与运算,最后输出结果。

以上是函数式接口的几种常见应用,它们都是Java 8中提供的常用的函数式接口。希望本文能对Java函数式编程有更深入的了解。