A **prime number** (or a **prime**) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself. However, 6 is composite because it is the product of two numbers (2 × 3) that are both smaller than 6. Primes are central in number theory because of the fundamental theorem of arithmetic: every natural number greater than 1 is either a prime itself or can be factorized as a product of primes that is unique up to their order. The property of being prime is called primality. A simple method of checking the primality of a given number `n`

, called trial division, tests whether `n`

is a multiple of any integer between 2 and .

In this post, I will demonstrate how to check primality of a number and then generate a sequence of prime numbers using Java Stream API based on two different criteria.

### Checking Primality

Let first check the canonical way of checking primality of a number n.

public class Prime { public static boolean isPrime(long n) { for (long i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } }

Lets now rewrite the method using Java Stream API.

public static boolean isPrime(long n) { return LongStream.rangeClosed(2, (long) Math.sqrt(n)) .allMatch(i -> n % i != 0); }

It’s look pretty simple and clean. We have created a `LongStream`

starting from 2 to square root of n and then checking if n is a multiple of the stream elements.

### Generate Prime Number Sequence in range (between `M`

and `N`

)

Now we will write a method to generate a sequence of prime numbers in between `M`

to `N`

. We will use the previous method `isPrime()`

to check primality.

public static List<Long> primeSequence(long min, long max) { return LongStream.range(min, max) .filter(Prime::isPrime) .boxed() .collect(Collectors.toList()); }

First, we have created a `LongStream`

ranging from the given parameters, `min`

to `max`

. Then we have applied `Stream.filter()`

to filter only the prime numbers by calling previously defined `isPrime()`

method. `LongStream`

is a sequence of primitive long-valued elements, so that we have boxed them by `Stream.boxed()`

and finally collected stream items inside a list and returned the list as the result.

Things to remember here, `LongStream.range(min, max)`

generates stream from `min`

(including) to `max`

(excluding). If you need to include `max`

, then `LongStream.rangeClosed(min, max)`

should be used.

Now calling the method with range [10, 20], `primeSequence(10, 20)`

, will output:

[11, 13, 17, 19]

### Generate first `N`

Prime Number Sequence

Now we will write another method which will return a sequence having first `N`

prime numbers.

public static List<Long> primeSequence(long n) { return LongStream.iterate(2, i -> i + 1) .filter(Prime::isPrime) .limit(n) .boxed() .collect(Collectors.toList()); }

Here, we have created infinite streams starting from 2 and adding items incrementing by 1, then applied `Stream.filter()`

to filter only prime numbers and then limiting the stream size to `N`

. Finally, boxed the primitive items, collected them to a list and returned the result. One important thing to consider here is the sequence of the operations. If you apply `Stream.limit()`

before `Stream.filter()`

, then output will be different because the stream will then be limited to have `N`

items and then will filter in between those. As a result you will not get the exact numbers of primes.

Now calling the method with value 10, `primeSequence(10)`

, will output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

### Summary

That’s all for now. So far, we have discussed about the definition of prime numbers and primality. Then we have written a method to check primality of a given number. And after that we have also written method to return a sequence of primes from m to n, and another one to return first n primes. For all three methods, we used Java Stream API.

Thanks for reading.

yaz says

March 23, 2019 at 8:15 amisPrime() is defined as isPrime(long n)

Monzurul Haque Shimul says

March 23, 2019 at 9:14 amThanks for the comment. I’ve updated the code.