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;
		Supplier<BigInteger> supplier7 = () -> factorial(new BigInteger("100"));

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

Result is:


This is old code with recursion:

public static BigInteger factorial(BigInteger x) {
    if (x.compareTo(new BigInteger("2")) < 0)
        return BigInteger.ONE;
        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.

java 8 ,java stream ,biginteger

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}