JAVA8 实现递归函数

JAVA8引入的lambda表达式是为了支持函数式编程,很多传统的编程风格都可以用lambda来进行实现,今天讲一下关于递归函数的实现。

  • 传统方式实现递归

以阶乘为例,实现阶乘的递归代码比较简单,如下所示

	private static int factorial(int x){
		if(x == 1 || x==0)
			return 1;
		return x*factorial(x-1);
	}
调用这个递归函数,就能实现阶乘功能。

  • lambda实现递归
lmabda是利用接口实现的,所以首先需要有一个接口来接收lambda表达式的函数,这里我们使用UnaryOperator<T>接口来说明问题,UnaryOperator<T>接口是JAVA8内置的函数式接口,UnaryOperator<T>接口接收一个T类型参数,并且返回一个T类型参数,如果递归函数的输入和输出有其他的特性,那么需要选择其他的函数式接口,JAVA8提供了一些,还可以自己实现函数式接口。按照传统的方式,我们来实现递归的逻辑,却发现会有编译错误。原因是此时的fact实际上是一个域而不是一个函数,这个域在这一行被完整的定义,在没有定义完成之前,没办法引用自身。此时可以通过this引用来指向fact。


private UnaryOperator<Integer> fact = x->((x==1 || x==0)? 1 : x * this.fact.apply(x-1));

静态成员变量,则需要使用类名来引用fact。整个代码如下所示

import java.util.function.UnaryOperator;

public class TestRecursion {
	public static void main(String[] args) {
		System.out.println(factorial(5));
		System.out.println(new TestRecursion().fact.apply(5));
		System.out.println(factStatic.apply(5));
		
	}
		
	private static int factorial(int x){
		if(x == 1 || x==0)
			return 1;
		return x*factorial(x-1);
	}
	
	private UnaryOperator<Integer> fact = x->((x==1 || x==0)? 1 : x * this.fact.apply(x-1));

	private static UnaryOperator<Integer> factStatic = x->((x==1 || x==0)? 1 : x * TestRecursion.factStatic.apply(x-1));
	
}

最后运行结果如图所示



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值