Java 四大核心函数式接口

四大核心函数式接口

消费型

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}
private static void consumer(){
    Consumer<String> consumer = o -> Objects.requireNonNull(o, "字符串不能为空");

    consumer.accept("wudg");
    consumer.accept(null);
    consumer.accept("");
}

供给型

package java.util.function;

@FunctionalInterface
public interface Supplier<T> {
    T get();
}
private static void supplier(){
    Supplier<String> supplier = () -> UUID.randomUUID().toString().replace("-", "");

    System.out.println(supplier.get());
}

函数型

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}
private static void function(){
    Function<String, String> function = s -> s.toUpperCase();

    System.out.println(function.apply("wudg"));
}

断言型

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}
private static void predicate(){
    Predicate<String> predicate = s -> s.isEmpty();

    System.out.println(predicate.test(""));
}
# java  jdk8 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×