I was trying to write a simple prime number program in Java 8. Below is the program. I wanted to reduce the code in isPrime()
as well. Is there something that filters the elements from 2
to n/2
, and then apply filter for n%i == 0
which would make isPrime
irrelevant?
import static java.util.stream.Collectors.toList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Stream1 {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 20);
// Prime number
System.out.println(numbers.stream()
.filter(Stream1::isPrime)
.collect(toList()));
}
public static boolean isPrime(int number) {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Prime number in Java: Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.
We can use the isPrime() function, which takes the number as input and returns true if the number is prime and false if it is not.
An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.
IntStream can be used to generate integer stream
public static boolean isPrime(int number) {
return !IntStream.rangeClosed(2, number/2).anyMatch(i -> number%i == 0);
}
or
public static boolean isPrime(int number) {
return IntStream.rangeClosed(2, number/2).noneMatch(i -> number%i == 0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With