JDK8之四大核心函数式接口

四大核心函数式接口

Consumer 接口

  1. 接口说明
    Consumer 接口是消费性接口,无返回值。Java8 中对 Consumer 的定义如下所示。
java 复制代码
/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@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); };
    }

使用说明

java 复制代码
public void handlerConsumer(Integer number, Consumer<Integer> consumer){
consumer.accept(number);
}
@Test
public void test1(){
this.handlerConsumer(10000, (i) -> System.out.println(i));
}

Supplier 接口

  1. 接口说明
    Supplier 接口是供给型接口,有返回值,Java8 中对 Supplier 接口的定义如下所示。
java 复制代码
@FunctionalInterface
public interface Supplier<T> {
T get();
}

使用示例

java 复制代码
public List<Integer> getNumberList(int num, Supplier<Integer> supplier){
List<Integer> list = new ArrayList<>();
for(int i = 0; i < num; i++){
list.add(supplier.get())
}
return list;
}
@Test
public void test2(){
List<Integer> numberList = this.getNumberList(10, () -> new Random().nextInt(100));
numberList.stream().forEach(System.out::println);
}

Function 接口

  1. 接口说明
    Function 接口是函数型接口,有返回值,Java8 中对 Function 接口的定义如下所示。
java 复制代码
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}

使用示例

java 复制代码
public String handlerString(String str, Function<String, String> func){
return func.apply(str);
}
@Test
public void test3(){
String str = this.handlerString("binghe", (s) -> s.toUpperCase());
System.out.println(str);
}

Predicate 接口

  1. 接口说明
    Predicate 接口是断言型接口,返回值类型为 boolean,Java8 中对 Predicate 接口的定义如下所示。
java 复制代码
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}

使用示例

java 复制代码
public List<String> filterString(List<String> list, Predicate<String> predicate){
List<String> strList = new ArrayList<>();
for(String str : list){
if(predicate.test(str)){
strList.add(str);
}
}
return strList;
}
@Test
public void test4(){
List<String> list = Arrays.asList("Hello", "Lambda", "binghe", "lyz", "World");
List<String> strList = this.filterString(list, (s) -> s.length() >= 5);
strList.stream().forEach(System.out::println);
}
相关推荐
IT 行者2 小时前
GitHub Spec Kit 实战(五):/speckit.tasks 怎么拆——Spec Kit 五部曲收官
java·ai编程·claude
(Charon)2 小时前
【C++ 面试高频基础:指针、引用、const、static、new/delete 总结】
java·开发语言
Yeats_Liao3 小时前
Feed流系统设计(三):数据模型与存储设计,从表结构到Redis收件箱
java·javascript·redis
JiaHao汤3 小时前
分布式事务方案全景:从理论到 Seata 落地
java·分布式·spring·spring cloud
色空大师4 小时前
【debug调试详解-idea】
java·ide·intellij-idea·调试·远程调试
程序猿阿越4 小时前
AutoMQ源码(一)读、写、Compaction
java·后端·源码
ywl4708120874 小时前
jwt生产token,简单版helloworld
java·数据库·spring
未若君雅裁4 小时前
生产问题排查与性能瓶颈定位:日志、监控、链路追踪、压测与Arthas
java·web安全
器灵科技4 小时前
AI视频工具实测:Seedance/可灵/HappyHorse谁最能打?
java·运维·数据库·人工智能·github
南部余额4 小时前
RabbitMQ 进阶:延迟队列完全指南
java·分布式·spring·rabbitmq