Over a million developers have joined DZone.

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

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

java 8 ,java stream ,biginteger

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}