FIZZBUZZ Solution in Java 8

Here is the FizzBuzz Solution in java 8 with different methods,

Here is the Before Java 8, simple solution:


public static void main(String[] args){
  for(int i= 1; i <= 20; i++){
   if(i % 15 == 0){
    System.out.println("FizzBuzz");
   }else if(i % 3 == 0){
    System.out.println("Fizz");
   }else if(i % 5 == 0){
    System.out.println("Buzz");
   }else{
    System.out.println(i);
   }
  }
 }


Now, Using Stream API, here different methods to display solved fizzbuzz solution,

Method1:
public static void main(String[] args) {
         fizzBuzzDisplay(1, 20;
  }
  private static void fizzBuzzDisplay(int i, int j) {
    // TODO Auto-generated method stub
           IntStream.rangeClosed(i,j)
                          .mapToObj(Test::transformNr)
                          .forEach(System.out::println);
   }

Method 2:
public static void main(String[] args) {
  // TODO Auto-generated method stub
  IntStream.rangeClosed(1, 20).mapToObj(num -> getWordForNum(num).orElse(Integer.toString(num)))
  .forEach(System.out::println);
 }
 private static Optional<String> getWordForNum(int num) {
  String word = "";
  if (isDiv(3).test(num))
   word += "Fizz";
  if (isDiv(5).test(num))
   word += "Buzz";
  return "".equals(word) ? Optional.empty() : Optional.of(word);
 }

 private static IntPredicate isDiv(int factor) {
  return arg -> (arg % factor) == 0;
 }

Method 3:
public static void main(String[] args) {
  // TODO Auto-generated method stub
  IntStream.rangeClosed(1, 20).mapToObj(A::fizzBuzz).forEach(System.out::println);
 }
 public static String fizzBuzz(int number) {
  if (number % 3==0 && number % 5 == 0) {
   return "FizzBuzz";
  } else if (number % 3 == 0) {
   return "Fizz";
  } else if (number % 5 == 0) {
   return "Buzz";
  }
  return Integer.toString(number);
 }

Method 4:
public static void main(String[] args) {
  // TODO Auto-generated method stub
  IntStream.range(1, 20)
        .mapToObj(n -> {
            if (n % 15 == 0) return "FizzBuzz";
            else if (n % 3 == 0) return "Fizz";
            else if (n % 5 == 0) return "Buzz";
            else return n;
        }).forEach(System.out::println);
 }

Mehtod 5:
public static void main(String[] args) {
  // TODO Auto-generated method stub
  IntStream.range(1, 20)
        .boxed()
        .map(x -> x+": " + (x%3==0? "Fizz": "") + (x%5==0? "Buzz": ""))
        .forEach(System.out::println);
 }

Output:

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz

Happy Coding !!!

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Training in Chennai Core Java 8 Training in Chennai Core Java 8 Training in Chennai JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete