lambda-2-function-Predicate

3 篇文章 0 订阅
3 篇文章 0 订阅

Predicate示例

Predicate简介

  • Predicate用于分配lambda表达式。
  • functional interface为功能性接口(函数式接口),有此注解的接口类只有一个对外接口方法。Predicate的接口为test(T t)。
  • 当我们将对象传递至这个方法时,它将通过分配的lambda表达式来评估对象。语法介绍:
public static void main (String[] args) {
	// 接受一个泛型参数,比较返回boolean值。
	Predicate<String> predicate = (v1) -> v1.equals("1");

	System.out.println(predicate.test("1"));
	System.out.println(predicate.test("2"));
}

可见Predicate代码如下。test方法的参数为泛型,创建Predicate对象时,可利用lambda书写test方法的逻辑。

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

Predicate实例

public static void main(String[] args) {
	Predicate<String> predicate = value -> value.equals("Amy");
	if (predicate.test("Amy")) {
		sout("Hello");
	}
}
// Hello

Function示例

Function-demo


public class FunctionTest {
	public static void main(String[] args) {
		FunctionTest test = new FunctionTest();
		System.out.println(test.method1(1, value -> value * 2, value -> value - 9));
        System.out.println(test.method2(1, value -> value * 2, value -> value - 9));
        System.out.println(test.method3(3, 4, (a, b) -> a + b));
        System.out.println(test.method4(2, 3, (a, b) -> a + b, value -> value - 10086));
	}
	
	public int method1(int count, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
        return function1.compose(function2).apply(count);
    }

    public int method2(int count, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
        return function1.andThen(function2).apply(count);
    }

	public int method3(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
		return biFunction.apply(a, b);
	}
	
	public int method4(int a, int b, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {
		// 因为BiFunction有两个变量,Function入参只有一个,所以BiFunction只有andThen这个方法,没有compose方法,且andThen参数为Function。
		return biFunction.andThen(function).apply(a, b);
	}
}

// 结果  -16  -9   7   -10081
// 其中compose为先将count传入function2,将返回的结果作为function1的参数。andThen反之。
// BiFunciton用于接收多个参数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值