Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java 8 Factorial

DZone's Guide to

Java 8 Factorial

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

· Java Zone ·
Free Resource

Atomist automates your software deliver experience. It's how modern teams deliver modern software.

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

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

Topics:
java 8 ,java stream ,biginteger

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}