Fizzbuzz Solution Inwards Coffee 8

FizzBuzz is 1 of the most famous programming enquiry from interviews, which is mostly used to weed out programmers who can't program. The work is deceptively elementary but you lot can't solve it if you lot don't know how to create programming logic. I dear it precisely for its simplicity. Now coming dorsum to instant component division of this article, Java 8. Its been to a greater extent than than a year, I recall it was March eighteen in conclusion twelvemonth when Java 8 was commencement released together with till appointment the most mutual enquiry I convey got is, how to larn novel features of Java 8? e.g. Optional, lambda seem or Stream. I recall best way to larn Java 8 novel features is the same equally best way to larn whatever novel programming linguistic communication i.e. solving mutual coding problem, implementing information structure, mutual algorithms together with implementing famous pattern patterns. I peculiarly discovery solving coding work together with first-class way to larn together with original Java 8 Streams. If you lot tin solve problems similar Fibonacci series together with couple of others using lambda seem together with streams, you lot 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 work disputation together with you lot 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 you lot write unit of measurement tests to depository fiscal establishment tally your solution, you lot must attain fifty-fifty if non asked during Interviews.



Solving FizzBuzz inwards Java 8

Here is the consummate solution of classic FizzBuzz work using novel features of Java 8. There are iii methods inwards this program, commencement solution is the simplest way to solve FizzBuzz inwards Java without using whatever of Java 8 novel feature, but instant together with 3rd solution uses Java 8 features similar lambda expressionOptional together with map() function together with 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 together with 5, if yeah nosotros provide FizzBuzz, otherwise nosotros depository fiscal establishment tally for divisibility yesteryear 3 together with 5, if its non divisible yesteryear whatever together with hence nosotros provide the same publish equally String.

Second solution is interesting because its written inwards Java 8. Optional is a novel concept together with course of didactics introduced inwards Java 8, mainly to bargain alongside cipher inwards amend way together with writing to a greater extent than expressive code which ensures that coder don't forget to depository fiscal establishment tally effect of a method if its Optional. For the purpose of this program, nosotros are using Optional equally Stream, equally you lot tin process it equally Stream of either 1 or 0 element. If Optional contains value together with hence it has 1 chemical cistron otherwise it has null element. The map() component division is written using lambda expression, it goes to each chemical cistron of  Optional together with depository fiscal establishment tally if it is divisible yesteryear 3, five or both together with accordingly provide "Fizz", "Buzz" or "FizzBuzz". Let's empathise this solution inwards piddling to a greater extent than particular :

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 work is creating Optional from the publish nosotros passed.
 - Second work is genuinely equivalent of next code

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

map is normally used to convert 1 type to another, likewise known equally transformation. You tin directly come across the logic of checking divisibility yesteryear 3 together with five together with how it produces "FizzBuzz" if publish is divisible yesteryear both 3 together with 5. If publish is non divisible yesteryear neither 3 or five together with hence this method volition provide an empty String.
 FizzBuzz is 1 of the most famous programming enquiry from interviews FizzBuzz Solution inwards Java 8

- Third work is telephone telephone to get() method which returns value if Optional contains whatever value otherwise it throw NoSuchElementException, Since nosotros know that later map() method, Optional volition either comprise "Fizz", "Buzz", "FizzBuzz" or empty String, nosotros are prophylactic to telephone telephone get() method here.

- Last work inwards method precisely depository fiscal establishment tally if effect is empty together with hence it provide original publish equally String otherwise effect itself.

Our instant method is likewise applying same logic but its piddling chip to a greater extent than expressive for Java programmer who are precisely started learning this novel way of coding. In this method, map method has exact the same logic equally our commencement method, but you lot come across nosotros convey cut back lot of boiler plate code related to method annunciation using lambda expression.

import java.util.Optional;  /**  * FizzBuzz work solution inwards Java 8. It's a classical work to filter  * programmers who can't program. Now you lot tin exercise this to depository fiscal establishment tally whether your  * Java candidate knows programming alongside Java 8 Streams or not.  *  * Problem : Write a method inwards Java which volition provide "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 elementary 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 together with 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 together with 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 piddling chip 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 ready of JUnit tests to depository fiscal establishment tally all iii solution of Java 8. You tin come across nosotros convey inwards full 4 bear witness cases, commencement to bear witness alongside numbers which are solely divisible yesteryear 3, instant to bear witness alongside publish which are divisible yesteryear 5, 3rd to bear witness alongside numbers which are divisible yesteryear both 3 together with five e.g. 15, thirty or 45 together with in conclusion 1 alongside numbers which are non divisible yesteryear either 3 or five e.g. 1 or 2. Together these 4 method comprehend all the requirement of FizzBuzz problem.

import org.junit.Assert; import org.junit.Test;  /**  * JUnit tests for our iii FizzBuzz solution, including ii inwards 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));     } }

together with hither is the effect of our JUnit test. You tin come across all 4 bear witness cases convey passed, which way all iii solution are right equally per specification of fizzbuzz problem, don't you lot dear the dark-green bar?
 FizzBuzz is 1 of the most famous programming enquiry from interviews FizzBuzz Solution inwards Java 8
This is the Netbeans's JUnit run window, you lot tin come across it clearly proverb all 4 tests are passed inside 62 milliseconds.


That's all nearly how to solve FizzBuzz inwards Java 8. As I said solving elementary programming problems or doing code katas are nifty way to larn together with original novel features of Java 8, especially lambda seem together with streams. FizzBuzz is 1 of the simplest of the work but even hence it teaches us how nosotros tin process Optional equally current together with exercise map component division to transform each chemical cistron of Optional. In the coming weeks nosotros volition likewise come across about to a greater extent than examples of solving classic programming problems using Java 8 features. BTW,  If you lot are eager to attain it yesteryear yourself, why non you lot endeavor to solve these 20 String algorithm problems using Java 8 Streams, lambdas together with other features.

Further Learning
The Complete Java MasterClass
examples)
  • What is default method inwards Java 8. (tutorial)
  • Are you lot cook for Java 8 Certification? (read more)
  • How to exercise Map component division inwards Java 8 (example)
  • 10 Examples of Stream API inwards Java (examples)
  • How to exercise Lambda Expression inwards Place of Anonymous course of didactics inwards Java 8 (solution)
  • 10 Java seven Feature to revisit earlier you lot startswith Java 8 (list)
  • 10 Good Tutorials to Learn Java 8 (list)
  • How to Read File inwards Java 8 inwards 1 line? (example)
  • How to filter List inwards Java 8 using Predicates? (solution)
  • What is Effective in conclusion variable inwards Java 8? (answer)
  • Java 8 Comparator Example alongside Lambdas (example)
  • Java 8 tutorials together with Books for FREE (resources)

  • Sumber https://javarevisited.blogspot.com/

    0 Response to "Fizzbuzz Solution Inwards Coffee 8"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel