In this post, we will see how to check if the number is prime or not with the help of Java 8 Streams API.
Easiest representation of Java 8 Streams power to test prime number... Check it out...!!! Share on X
Let’s say: In this particular example, we are checking if ‘5’ is a prime number or not.
Note: you can specify any number you would like to check for in place of 5 in below example.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import java.util.stream.IntStream; public class CheckIfNumberIsPrime { static Integer numberToCheckForPrime = 5; public static void main(String args[]){ System.out.println("Is it a prime number: "+isPrime(numberToCheckForPrime)); } private static boolean isPrime(int number) { return number > 1 && IntStream.range(2, number).noneMatch(i -> number%i==0); } } |
Output:
1 | Is it a prime number: true |
Easiest representation of Java 8 Streams power to test prime number... Check it out...!!! Share on X
That’s it, Java 8 Streams API is so powerful and notice how easily it simplified the way of checking the Prime number.
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams
helo sir ,
i learn java concept from your website techndeck.com.Thanku sir…This best java tutorrioal as compared another tutorrial websites…
Thanks Anurag. I am glad, I was helpful.