In this post, we will see how to generate prime numbers using Java 8 Streams API?”.

Easiest representation of generating prime numbers using Java 8 Streams...!!! Share on X

In this tutorial, we are going to cover below topics:

  1. what is Prime Number?
  2. How to generate Prime Numbers using Java 8 Streams?

 

Let’s begin:

1. What is Prime Number?

As per wiki, “A Prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers”.

          OR

“A prime number is a whole number greater than 1 whose only factors are 1 and itself”.

Example: 5 is a prime number because 5 is greater than 1 and it can only be divided by 1 and 5.

2. How to generate Prime Number using Java 8 Streams?

package org.personal.samples;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class GeneratePrimeNumberInJava8 {

    public static void main(String[] args) {
        System.out.println("Prime numbers until 50:\n" + primeNumbersUnTil(50));
        System.out.println("\nPrime numbers within 10 and 31:\n" + primeNumbersInRange(10, 31));
    }

    //Generating prime numbers till the number we want. 
    public static List < Integer > primeNumbersUnTil(int n) {
        return IntStream
            .rangeClosed(2, n)
            .filter(x -> isPrime(x)).boxed()
            .collect(Collectors.toList());
    }

    //Generating prime numbers within the specific range. 
    public static List < Integer > primeNumbersInRange(int startingNumber, int endingNumber) {
        return IntStream
            .rangeClosed(startingNumber, endingNumber)
            .filter(x -> isPrime(x)).boxed()
            .collect(Collectors.toList());
    }

    //Java 8 way to check if the number is prime or not 
    private static boolean isPrime(int number) {
        return number > 1 && IntStream
            .range(2, number)
            .noneMatch(i -> number % i == 0);
    }
}

 

Output:

Prime numbers until 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Prime numbers within 10 and 31:
[11, 13, 17, 19, 23, 29, 31]

 

That’s it, Java 8 Streams API is so powerful and notice how easily it simplified the way of generating the Prime numbers.

Easiest representation of generating prime numbers using Java 8 Streams...!!! Share on X

 

Do you like this Post? – then check my other helpful posts:

Other Useful References:

 

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts