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:
- what is Prime Number?
- 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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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:
1 2 3 4 5 | 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:
Very nice informative post. thanks for the post.