Replace loop with IntStream.range(start, number);

Hello,

before java 8 if we want to find that a number is prime or not, definitely we have to go through loop given example below

private static boolean isPrime(int number) {
if(number < 2) return false;
for(int i=2; i<number; i++){
if(number % i == 0) return false;
}
return true;
}

 

but after java 8 it is as simple as

private static boolean isPrime(int number) {
return number > 1
&& IntStream.range(2, number).noneMatch(
index -> number % index == 0);
}

IntStream range method go through the range and it and it’s noneMatch method takes a PredicateĀ  and returns true if our condition is satisfied

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s