Over a million developers have joined DZone.

Java 8 Factorial

Check out this neat example of a Java 8 factorial that explores streams.

· Java Zone

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

Here is the code using streams:

package com.bos;

import java.math.BigInteger;
import java.util.Date;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class Factorial {

	static class Pair {
		final BigInteger num;
		final BigInteger value;

		Pair(BigInteger num, BigInteger value) {
			this.num = num;
			this.value = value;
		}
	}

	public static BigInteger factorial(BigInteger num) {
		Stream<Pair> allFactorials = Stream.iterate(new Pair(BigInteger.ONE, BigInteger.ONE),
				x -> new Pair(x.num.add(BigInteger.ONE), x.value.multiply(x.num.add(BigInteger.ONE))));
		// return allFactorials.limit(num.longValue()).reduce((previous,
		// current) -> current).get().value;
		return allFactorials.filter((x) -> x.num.equals(num)).findAny().get().value;
	}

	public static void main(String[] args) {
		Date startDate = new Date();
		long startTime = System.nanoTime();
		Supplier<String> supplier1 = () -> "Started at " + startDate;
		System.out.println(supplier1.get());
		
		Supplier<BigInteger> supplier7 = () -> factorial(new BigInteger("100"));
		System.out.println(supplier7.get());

		Date endDate = new Date();
		long totalTime = System.nanoTime() - startTime;
		Supplier<String> supplier2 = () -> "Ended at " + endDate + " total time=" + totalTime + " nanosec";
		System.out.println(supplier2.get());
	}
}

Result is:

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

This is old code with recursion:

public static BigInteger factorial(BigInteger x) {
    if (x.compareTo(new BigInteger("2")) < 0)
        return BigInteger.ONE;
    else
        return x.multiply(factorial(x.subtract(BigInteger.ONE)));
}

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:
java 8 ,java stream ,biginteger

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}