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

Published by nareshjavatips

Java Edicted

Leave a comment