Fizzbuzz Solution Inward Coffee 8

FizzBuzz is i of the most famous programming query from interviews, which is to a greater extent than oftentimes than non used to weed out programmers who can't program. The employment is deceptively uncomplicated but y'all can't solve it if y'all don't know how to construct programming logic. I honey it precisely for its simplicity. Now coming dorsum to instant component of this article, Java 8. Its been to a greater extent than than a year, I shout upwards it was March xviii in conclusion twelvemonth when Java 8 was starting fourth dimension released as well as till appointment the most mutual query I bring got is, how to acquire novel features of Java 8? e.g. Optional, lambda aspect or Stream. I shout upwards best way to acquire Java 8 novel features is the same equally best way to acquire whatever novel programming linguistic communication i.e. solving mutual coding problem, implementing information structure, mutual algorithms as well as implementing famous blueprint patterns. I especially notice solving coding employment as well as fantabulous way to acquire as well as master copy Java 8 Streams. If y'all tin flame solve problems similar Fibonacci series as well as couple of others using lambda aspect as well as 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 employment contention as well as y'all demand to solve it using Java 8.

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

Bonus points if y'all write unit of measurement tests to depository fiscal establishment stand upwards for your solution, y'all must attain fifty-fifty if non asked during Interviews.



Solving FizzBuzz inwards Java 8

Here is the consummate solution of classic FizzBuzz employment using novel features of Java 8. There are 3 methods inwards this program, starting fourth dimension solution is the simplest way to solve FizzBuzz inwards Java without using whatever of Java 8 novel feature, but instant as well as 3rd solution uses Java 8 features similar lambda expressionOptional as well as map() function as well as novel way of writing code.  First solution is self explanatory, nosotros are checking if seat out is divisible yesteryear 15, which way it divisible yesteryear both 3 as well as 5, if yep nosotros furnish FizzBuzz, otherwise nosotros depository fiscal establishment stand upwards for for divisibility yesteryear 3 as well as 5, if its non divisible yesteryear whatever thence nosotros furnish the same seat out equally String.

Second solution is interesting because its written inwards Java 8. Optional is a novel concept as well as flat introduced inwards Java 8, mainly to bargain amongst nada inwards amend way as well as writing to a greater extent than expressive code which ensures that coder don't forget to depository fiscal establishment stand upwards for consequence of a method if its Optional. For the purpose of this program, nosotros are using Optional equally Stream, equally y'all tin flame process it equally Stream of either 1 or 0 element. If Optional contains value thence it has i chemical constituent otherwise it has null element. The map() component is written using lambda expression, it goes to each chemical constituent of  Optional as well as depository fiscal establishment stand upwards for if it is divisible yesteryear 3, five or both as well as accordingly furnish "Fizz", "Buzz" or "FizzBuzz". Let's empathize this solution inwards niggling to a greater extent than item :

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

 - First employment is creating Optional from the seat out nosotros passed.
 - Second employment is genuinely equivalent of next code

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

map is unremarkably used to convert i type to another, likewise known equally transformation. You tin flame straight off run across the logic of checking divisibility yesteryear 3 as well as five as well as how it produces "FizzBuzz" if seat out is divisible yesteryear both 3 as well as 5. If seat out is non divisible yesteryear neither 3 or five thence this method volition furnish an empty String.
 FizzBuzz is i of the most famous programming query from interviews FizzBuzz Solution inwards Java 8

- Third employment 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 condom to telephone telephone get() method here.

- Last employment inwards method precisely depository fiscal establishment stand upwards for if consequence is empty thence it furnish original seat out equally String otherwise consequence itself.

Our instant method is likewise applying same logic but its niggling fleck 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 starting fourth dimension method, but y'all run across nosotros bring trim lot of boiler plate code related to method announcement using lambda expression.

import java.util.Optional;  /**  * FizzBuzz employment solution inwards Java 8. It's a classical employment to filter  * programmers who can't program. Now y'all tin flame exercise this to depository fiscal establishment stand upwards for whether your  * Java candidate knows programming amongst Java 8 Streams or not.  *  * Problem : Write a method inwards Java which volition furnish "Fizz" if the seat out is  * dividable yesteryear 3 "Buzz" if the seat out is dividable yesteryear five "FizzBuzz" if the  * seat out is dividable yesteryear xv the same seat out 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 seat out      * @return Fizz if seat out divisible yesteryear 3, Buzz if seat out divisible yesteryear five      * FizzBuzz if divisible yesteryear both 3 as well as 5, or else the same seat out      */     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 as well as Stream map() component is      * genuinely useful here.      *      * @param seat out      * @return Fizz, Buzz, FizzBuzz or the seat out itself      */     public static String fizzBuzzInJava8(int number) {         String consequence = 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 niggling fleck 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 gear upwards of JUnit tests to depository fiscal establishment stand upwards for all 3 solution of Java 8. You tin flame run across nosotros bring inwards full 4 essay cases, starting fourth dimension to essay amongst numbers which are exclusively divisible yesteryear 3, instant to essay amongst seat out which are divisible yesteryear 5, 3rd to essay amongst numbers which are divisible yesteryear both 3 as well as five e.g. 15, xxx or 45 as well as in conclusion i amongst numbers which are non divisible yesteryear either 3 or five e.g. 1 or 2. Together these 4 method encompass all the requirement of FizzBuzz problem.

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

as well as hither is the consequence of our JUnit test. You tin flame run across all 4 essay cases bring passed, which way all 3 solution are right equally per specification of fizzbuzz problem, don't y'all honey the greenish bar?
 FizzBuzz is i of the most famous programming query from interviews FizzBuzz Solution inwards Java 8
This is the Netbeans's JUnit run window, y'all tin flame run across it clearly maxim all 4 tests are passed inside 62 milliseconds.


That's all virtually how to solve FizzBuzz inwards Java 8. As I said solving uncomplicated programming problems or doing code katas are bully way to acquire as well as master copy novel features of Java 8, especially lambda aspect as well as streams. FizzBuzz is i of the simplest of the employment but silent it teaches us how nosotros tin flame process Optional equally current as well as exercise map component to transform each chemical constituent of Optional. In the coming weeks nosotros volition likewise run across roughly 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 effort to solve these 20 String algorithm problems using Java 8 Streams, lambdas as well as other features.

Further Learning
The Complete Java MasterClass
examples)
  • What is default method inwards Java 8. (tutorial)
  • Are y'all create for Java 8 Certification? (read more)
  • How to exercise Map component inwards Java 8 (example)
  • 10 Examples of Stream API inwards Java (examples)
  • How to exercise Lambda Expression inwards Place of Anonymous flat inwards Java 8 (solution)
  • 10 Java seven Feature to revisit earlier y'all startswith Java 8 (list)
  • 10 Good Tutorials to Learn Java 8 (list)
  • How to Read File inwards Java 8 inwards i line? (example)
  • How to filter List inwards Java 8 using Predicates? (solution)
  • What is Effective concluding variable inwards Java 8? (answer)
  • Java 8 Comparator Example amongst Lambdas (example)
  • Java 8 tutorials as well as Books for FREE (resources)
  • 0 Response to "Fizzbuzz Solution Inward Coffee 8"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel