How to generate prime numbers using lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

A prime number is a number that is greater than 1 and divided by 1 or itself only. It other words, it can't be divided by other numbers than itself or 1. The generation of prime numbers is 2, 3, 5, 7, 11, 13, 17 and etc.

In the below example, we can generate the prime numbers with the help of Stream API and lambda expressions.

Example

import java.util.*;
import java.util.stream.*;

public class PrimeNumberLambdaTest {
   public static void main(String[] args) {
      List<Integer> generate = PrimeNumberLambdaTest.generate(10);
      System.out.println(generate);
   }
   public static List<Integer> generate(int series) {
      Set<Integer> set = new TreeSet<>();
      return Stream.iterate(1, i -> ++i)
              .filter(i -> i %2 != 0) // lambda expression
              .filter(i -> {
                  set.add(i);
                  return 0 == set.stream()
                           .filter(p -> p != 1)
                           .filter(p -> !Objects.equals(p, i))
                           .filter(p -> i % p == 0)
                           .count();
              })
              .limit(series)
            .collect(Collectors.toList());
   }
}

Output

[1, 3, 5, 7, 11, 13, 17, 19, 23, 29]
raja
Published on 08-Jan-2020 09:36:33
Advertisements