- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to generate prime numbers using lambda expression in Java?
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]
Advertisements