Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





Java - Code Samples

 Sample 1. Write a Program that gets a set of numbers , filters out the non prime numbers , calculate the factorial of each prime number and then finds the average of all factorials using Lambda expressions

public class BuggyBread1 {
   
   public static void main(String args[]) {
      
      // Declare and Initialize the Collection
      Set<Integer> intSet = new HashSet<Integer>();

      // Add Elements
      intSet.add(1);
      intSet.add(2);
      intSet.add(3);
      intSet.add(4);
      intSet.add(5);

      double averageOfNonPrimeFactorials = intSet.stream().filter(p->checkIfPrime(p)).collect(Collectors.averagingInt(p->calculateFactorial(p)));
      
      System.out.println(averageOfNonPrimeFactorials );
   }
   
   static private boolean checkIfPrime(int num){
      for(int count=2;count < num;count++){
         if(num % count == 0){
            return false;
         }
      }
      return true;
   }
   
   static private int calculateFactorial(int num){
      int factorial = 1;
      for(int count=num;count > 0;count--){
         factorial = factorial * count;
      }
      return factorial;
   }
}

   Like      Feedback     java 8  lambda expressions  lambda  filter  Collectors  factorial  prime number



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner