This is the second solution to find the missing prime numbers from any given sequence of integers. This solution uses the Lambda expression with single abstract method. The solution also uses the range, filter, foreach methods of IntStream.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.IntStream;
//Define the functional interface with SAM 'Checkprime'
interface Checkprime {
public boolean prime(int tmp);
}
public class MissingPrimeNumbersUsingStream {
public static void main(String[] args) {
// The input sequence of integers is numList
ArrayList<Integer> numList = new ArrayList<>(Arrays.asList(2, 11, 20, 25, 32, 37));
System.out.println("The given list of Integers sequence (I/P)");
numList.stream().forEach(x -> System.out.print(x + " "));
// Define the Lambda expression for the functional interface Checkprime
Checkprime Cp = ((num) -> {
/* Initialize the lower and upper boundary values in the for loop */
int bvalToCheck = (int) Math.sqrt(num);
for (int i = 2; i <= bvalToCheck; i++)
if (num % i == 0)
return false;
return true;
});
System.out.println("\nFinal Missing Prime Numbers from the above sequence (O/P)");
/*
* Call the IntStream within range two successive numbers from the list, and
* within that range check whether each number is prime or not.
*/
for (int i = 0; i < numList.size() - 1; i++) {
IntStream.range(numList.get(i) + 1, numList.get(i + 1))
.filter(j -> Cp.prime(j))
.forEach(x -> System.out.print(x + " "));
}
}
}
OUTPUT-
The given list of Integers sequence (I/P)
2 11 20 25 32 37
Final Missing Prime Numbers from the above sequence (O/P)
3 5 7 13 17 19 23 29 31

Leave a comment