Java 函数式编程

函数式接口 java.util.function

  • Predicate: 有输入且只输出布尔值

a predicate (boolean-valued function) of one argument,

 @FunctionalInterface
public interface Predicate<T> {
 	boolean test(T t);
 }

Predicate接口包含negate(非)、and(与)和or(非)方法

default Predicate<T> negate() {
   return (t) -> !test(t);
}

default Predicate<T> and(Predicate<? super T> other) {
	Objects.requireNonNull(other);
	return (t) -> test(t) && other.test(t);
}

default Predicate<T> or(Predicate<? super T> other) {
   Objects.requireNonNull(other);
   return (t) -> test(t) || other.test(t);
}

  • Function:有输入有输出

a function that accepts one argument and produces a result

@FunctionalInterface
public interface Function<T, R> {
	R apply(T t);
}
  • Consumer:有输入无输出
@FunctionalInterface
public interface Consumer<T> {
	void accept(T t);
}
  • Supplier:无输入有输出
@FunctionalInterface
public interface Supplier<T> {
    T get();
}

  • Operator:输入和输出为相同类型
    • UnaryOperator

    Represents an operation on a single operand that produces a result of the same type as its operand.

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
    static <T> UnaryOperator<T> identity() {
        return t -> t;
    }
}
  • BinaryOperator

    Represents an operation upon two operands of the same type, producing a result of the same type as the operands.

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
}

使用Lambda表达式实现函数式接口的抽象方法:

Predicate<Integer> empty = x -> x > 0;
System.out.println(empty.test(1));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值