Fizzbuzz Solution Inwards Coffee 8

FizzBuzz is i of the most famous programming inquiry from interviews, which is by in addition to large used to weed out programmers who can't program. The occupation is deceptively uncomplicated but y'all can't solve it if y'all don't know how to construct programming logic. I dear it exactly for its simplicity. Now coming dorsum to minute component division of this article, Java 8. Its been to a greater extent than than a year, I recall it was March xviii in conclusion yr when Java 8 was kickoff released in addition to till appointment the most mutual inquiry I bring got is, how to acquire novel features of Java 8? e.g. Optional, lambda human face or Stream. I recall best way to acquire Java 8 novel features is the same every bit best way to acquire whatsoever novel programming linguistic communication i.e. solving mutual coding problem, implementing information structure, mutual algorithms in addition to implementing famous blueprint patterns. I specially detect solving coding occupation in addition to first-class way to acquire in addition to master copy Java 8 Streams. If y'all tin dismiss solve problems similar Fibonacci series in addition to couple of others using lambda human face in addition to streams, y'all volition progress quickly. Remember, Stream is a novel way to write code without using for loop. Now coming dorsum to our FizzBuzz problem, hither is the occupation arguing in addition to y'all demand to solve it using Java 8.

Problem : For a given natural publish greater than null return:
    “Fizz” if the publish is dividable yesteryear 3
    “Buzz” if the publish is dividable yesteryear 5
    “FizzBuzz” if the publish is dividable yesteryear 15
    the same publish if publish is neither divisible yesteryear 3 nor 5.

Bonus points if y'all write unit of measurement tests to banking enterprise fit your solution, y'all must attain fifty-fifty if non asked during Interviews.



Solving FizzBuzz inward Java 8

Here is the consummate solution of classic FizzBuzz occupation using novel features of Java 8. There are 3 methods inward this program, kickoff solution is the simplest way to solve FizzBuzz inward Java without using whatsoever of Java 8 novel feature, but minute in addition to tertiary solution uses Java 8 features similar lambda expressionOptional in addition to map() function in addition to novel way of writing code.  First solution is self explanatory, nosotros are checking if publish is divisible yesteryear 15, which way it divisible yesteryear both 3 in addition to 5, if yep nosotros furnish FizzBuzz, otherwise nosotros banking enterprise fit for divisibility yesteryear 3 in addition to 5, if its non divisible yesteryear whatsoever thence nosotros furnish the same publish every bit String.

Second solution is interesting because its written inward Java 8. Optional is a novel concept in addition to shape introduced inward Java 8, mainly to bargain alongside nix inward meliorate way in addition to writing to a greater extent than expressive code which ensures that coder don't forget to banking enterprise fit effect of a method if its Optional. For the purpose of this program, nosotros are using Optional every bit Stream, every bit y'all tin dismiss process it every bit Stream of either 1 or 0 element. If Optional contains value thence it has i chemical cistron otherwise it has null element. The map() component division is written using lambda expression, it goes to each chemical cistron of  Optional in addition to banking enterprise fit if it is divisible yesteryear 3, five or both in addition to accordingly furnish "Fizz", "Buzz" or "FizzBuzz". Let's sympathise this solution inward picayune to a greater extent than item :

public static String fizzBuzzInJava8(int number) {         String effect = Optional.of(number)                 .map(n -> (n % 3 == 0 ? "Fizz" : "") + (n % 5 == 0 ? "Buzz" : ""))                 .get();         return result.isEmpty() ? Integer.toString(number) : result;   }

 - First draw of piece of work is creating Optional from the publish nosotros passed.
 - Second draw of piece of work is genuinely equivalent of next code

public String map(int number){    return  (n % 3 == 0 ? "Fizz" : "") + (n % 5 == 0 ? "Buzz" : ""); }

map is commonly used to convert i type to another, too known every bit transformation. You tin dismiss forthwith come across the logic of checking divisibility yesteryear 3 in addition to five in addition to how it produces "FizzBuzz" if publish is divisible yesteryear both 3 in addition to 5. If publish is non divisible yesteryear neither 3 or five thence this method volition furnish an empty String.
 FizzBuzz is i of the most famous programming inquiry from interviews FizzBuzz Solution inward Java 8

- Third draw of piece of work is telephone telephone to get() method which returns value if Optional contains whatsoever value otherwise it throw NoSuchElementException, Since nosotros know that afterwards map() method, Optional volition either incorporate "Fizz", "Buzz", "FizzBuzz" or empty String, nosotros are rubber to telephone telephone get() method here.

- Last draw of piece of work inward method merely banking enterprise fit if effect is empty thence it furnish original publish every bit String otherwise effect itself.

Our minute method is too applying same logic but its picayune fight to a greater extent than expressive for Java programmer who are exactly started learning this novel way of coding. In this method, map method has exact the same logic every bit our kickoff method, but y'all come across nosotros bring trim down lot of boiler plate code related to method proclamation using lambda expression.

import java.util.Optional;  /**  * FizzBuzz occupation solution inward Java 8. It's a classical occupation to filter  * programmers who can't program. Now y'all tin dismiss usage this to banking enterprise fit whether your  * Java candidate knows programming alongside Java 8 Streams or not.  *  * Problem : Write a method inward Java which volition furnish "Fizz" if the publish is  * dividable yesteryear 3 "Buzz" if the publish is dividable yesteryear five "FizzBuzz" if the  * publish is dividable yesteryear fifteen the same publish if no other requirement is  * fulfilled.  *  * @author Javin Paul  */ public class FizzBuzzJava8 {      public static void main(String args[]) {         System.out.println("FizzBuzz using uncomplicated Java : " + fizzBuzz(3));         System.out.println("FizzBuzz solution using Java 8  : " + fizzBuzzInJava8(15));     }      /**      * Simple Java solution of FizzBuzz Problem      *      * @param publish      * @return Fizz if publish divisible yesteryear 3, Buzz if publish divisible yesteryear five      * FizzBuzz if divisible yesteryear both 3 in addition to 5, or else the same publish      */     public static String fizzBuzz(int number) {         if (number % 15 == 0) {             return "FizzBuzz";         } else if (number % 3 == 0) {             return "Fizz";         } else if (number % 5 == 0) {             return "Buzz";         }         return Integer.toString(number);     }      /**      * FizzBuzz Solution using Java 8 Optional, map in addition to Stream map() component division is      * genuinely useful here.      *      * @param publish      * @return Fizz, Buzz, FizzBuzz or the publish itself      */     public static String fizzBuzzInJava8(int number) {         String effect = Optional.of(number)                 .map(n -> (n % 3 == 0 ? "Fizz" : "") + (n % 5 == 0 ? "Buzz" : ""))                 .get();         return result.isEmpty() ? Integer.toString(number) : result;     }      /*      * Another Java 8 solution, this fourth dimension its picayune fight to a greater extent than expressive      * for Java 8 newbie.      */     public static String fizzBuzzSolutionJava8(int input) {         return Optional.of(input)                 .map(i -> {                     if (i % (3 * 5) == 0) {                         return "FizzBuzz";                     } else if (i % 3 == 0) {                         return "Fizz";                     } else if (i % 5 == 0) {                         return "Buzz";                     } else {                         return Integer.toString(i);                     }                 }).get();     }  }



JUnit Test for FizzBuzz problem

Here is our laid of JUnit tests to banking enterprise fit all 3 solution of Java 8. You tin dismiss come across nosotros bring inward full 4 examine cases, kickoff to examine alongside numbers which are entirely divisible yesteryear 3, minute to examine alongside publish which are divisible yesteryear 5, tertiary to examine alongside numbers which are divisible yesteryear both 3 in addition to five e.g. 15, xxx or 45 in addition to in conclusion i alongside numbers which are non divisible yesteryear either 3 or five e.g. 1 or 2. Together these iv method encompass all the requirement of FizzBuzz problem.

import org.junit.Assert; import org.junit.Test;  /**  * JUnit tests for our 3 FizzBuzz solution, including ii inward Java 8.   * @author WINDOWS 8  */ public class FizzBuzzJava8Test {      @Test     public void testWithNumberIsDividableBy3() {         Assert.assertEquals("Fizz", FizzBuzzJava8.fizzBuzz(3));         Assert.assertEquals("Fizz", FizzBuzzJava8.fizzBuzzInJava8(3));         Assert.assertEquals("Fizz", FizzBuzzJava8.fizzBuzzSolutionJava8(3));     }      @Test     public void testWithNumberIsDividableBy5() {         Assert.assertEquals("Buzz", FizzBuzzJava8.fizzBuzz(5));         Assert.assertEquals("Buzz", FizzBuzzJava8.fizzBuzzInJava8(5));         Assert.assertEquals("Buzz", FizzBuzzJava8.fizzBuzzSolutionJava8(5));     }      @Test     public void testWithNumberIsDividableBy15() {         Assert.assertEquals("FizzBuzz", FizzBuzzJava8.fizzBuzz(15));         Assert.assertEquals("FizzBuzz", FizzBuzzJava8.fizzBuzzInJava8(15));         Assert.assertEquals("FizzBuzz", FizzBuzzJava8.fizzBuzzSolutionJava8(15));         Assert.assertEquals("FizzBuzz", FizzBuzzJava8.fizzBuzz(45));         Assert.assertEquals("FizzBuzz", FizzBuzzJava8.fizzBuzzInJava8(45));         Assert.assertEquals("FizzBuzz", FizzBuzzJava8.fizzBuzzSolutionJava8(45));     }      @Test     public void testOtherNumbers() {         Assert.assertEquals("1", FizzBuzzJava8.fizzBuzz(1));         Assert.assertEquals("1", FizzBuzzJava8.fizzBuzzInJava8(1));         Assert.assertEquals("1", FizzBuzzJava8.fizzBuzzSolutionJava8(1));         Assert.assertEquals("7", FizzBuzzJava8.fizzBuzz(7));         Assert.assertEquals("7", FizzBuzzJava8.fizzBuzzInJava8(7));         Assert.assertEquals("7", FizzBuzzJava8.fizzBuzzSolutionJava8(7));     } }

in addition to hither is the effect of our JUnit test. You tin dismiss come across all iv examine cases bring passed, which way all 3 solution are right every bit per specification of fizzbuzz problem, don't y'all dear the light-green bar?
 FizzBuzz is i of the most famous programming inquiry from interviews FizzBuzz Solution inward Java 8
This is the Netbeans's JUnit run window, y'all tin dismiss come across it clearly maxim all 4 tests are passed inside 62 milliseconds.


That's all close how to solve FizzBuzz inward Java 8. As I said solving uncomplicated programming problems or doing code katas are swell way to acquire in addition to master copy novel features of Java 8, especially lambda human face in addition to streams. FizzBuzz is i of the simplest of the occupation but soundless it teaches us how nosotros tin dismiss process Optional every bit current in addition to usage map component division to transform each chemical cistron of Optional. In the coming weeks nosotros volition too come across approximately to a greater extent than examples of solving classic programming problems using Java 8 features. BTW,  If y'all are eager to attain it yesteryear yourself, why non y'all assay to solve these 20 String algorithm problems using Java 8 Streams, lambdas in addition to other features.

Further Learning
The Complete Java MasterClass
examples)
  • What is default method inward Java 8. (tutorial)
  • Are y'all fix for Java 8 Certification? (read more)
  • How to usage Map component division inward Java 8 (example)
  • 10 Examples of Stream API inward Java (examples)
  • How to usage Lambda Expression inward Place of Anonymous shape inward Java 8 (solution)
  • 10 Java vii Feature to revisit earlier y'all startswith Java 8 (list)
  • 10 Good Tutorials to Learn Java 8 (list)
  • How to Read File inward Java 8 inward i line? (example)
  • How to filter List inward Java 8 using Predicates? (solution)
  • What is Effective in conclusion variable inward Java 8? (answer)
  • Java 8 Comparator Example alongside Lambdas (example)
  • Java 8 tutorials in addition to Books for FREE (resources)
  • Komentar

    Postingan populer dari blog ini

    Difference Betwixt Struts Validatorform Vs Validatoractionform - Interview Question

    How To Convert Inputstream To Byte Array Inwards Coffee - Two Examples

    Difference Betwixt Fileinputstream Together With Filereader Inwards Coffee | Inputstream Vs Reader