Wednesday, May 8, 2024
HomeJavaFind out how to remedy FizzBuzz Downside in Java 8? Stream.map() Instance

Find out how to remedy FizzBuzz Downside in Java 8? Stream.map() Instance


FizzBuzz is likely one of the most well-known programming questions from interviews, which is mostly used to weed out programmers who cannot program. The issue is deceptively easy however you possibly can’t remedy it if you do not know how you can construct programming logic. I like it only for its simplicity. Now coming again to the second a part of this text, Java 8. It has been greater than a 12 months, I believe it was March 18 final 12 months when Java 8 was first launched and thus far, the commonest query I’ve obtained is, how you can be taught new options of Java 8? like Optionally available, lambda expression, or Stream. I believe one of the simplest ways to be taught Java 8 new options is similar as one of the simplest ways to be taught any new programming language like fixing frequent coding issues, implementing knowledge construction, frequent algorithms, and implementing well-known design patterns.

I notably discover fixing coding issues and a very good approach to be taught and grasp Java 8 Streams. In case you can remedy issues just like the 
Fibonacci sequence and a couple of others utilizing lambda expressions and streams, you’ll progress shortly. Keep in mind, Stream is a brand new approach to write code with out utilizing for loop. Now coming again to our FizzBuzz drawback, right here is the issue assertion and you want to remedy it utilizing Java 8.

Downside: For a given pure quantity larger than zero return:

  •     “Fizz” if the quantity is dividable by 3
  •     “Buzz” if the quantity is dividable by 5
  •     “FizzBuzz” if the quantity is dividable by 15
  •      Identical quantity if the quantity is neither divisible by 3 nor 5.

Bonus factors when you write unit assessments to test your resolution, it’s essential to do even when not requested throughout Interviews.

Btw, in case you are not acquainted with new Java 8 options like Successfully remaining variable then I counsel you first undergo a complete and up-to-date Java course like The Full Java MasterClass on Udemy. It is also very inexpensive and you should purchase in simply $10 on Udemy gross sales which occur from time to time.

Fixing FizzBuzz in Java 8 – Instance

Right here is the entire resolution to the traditional FizzBuzz drawback utilizing the brand new options of Java 8. There are three strategies on this program, the primary resolution is the only approach to remedy FizzBuzz in Java with out utilizing any of Java 8 new options, however the second and third resolution makes use of Java 8 options like lambda expressionOptionally available, and map() operate and a brand new approach of writing code.

The primary resolution is self-explanatory, we’re checking if the quantity is divisible by 15, which suggests it’s divisible by each 3 and 5, if sure we return FizzBuzz, in any other case, we test for divisibility by 3 and 5, if it is not divisible by any then we return the identical quantity as String.

The second resolution is attention-grabbing as a result of it is written in Java 8. Optionally available is a brand new idea and sophistication launched in Java 8, primarily to take care of null in a greater approach and writing extra expressive code which ensures that the coder does not neglect to test the results of a way if it is Optionally available.

For the aim of this program, we’re utilizing Optionally available as Stream, as you possibly can deal with it as Stream of both 1 or 0 parts. If Optionally available comprises a price then it has one factor in any other case it has zero parts. 

The map() operate is written utilizing a lambda expression, it goes to every factor of  Optionally available and checks whether it is divisible by 3, 5, or each and accordingly returns “Fizz”, “Buzz” or “FizzBuzz”. Let’s perceive this resolution in little extra element :

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

 – The primary line is creating Optionally available from the quantity we handed.
 – Second-line is definitely equal to following code

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

the map is normally used to transform one kind to a different, often known as transformation. Now you can see the logic of checking divisibility by 3 and 5 and the way it produces “FizzBuzz” if the quantity is divisible by each 3 and 5. If the quantity shouldn’t be divisible by neither 3 or 5 then this methodology will return an empty String.

FizzBuzz Solution in Java 8 using Streams

The third line calls to get() methodology which returns the worth if Optionally available comprises any worth in any other case it throws NoSuchElementException, Since we all know that after map() methodology, Optionally available will both comprise “Fizz”, “Buzz”, “FizzBuzz” or empty String, we’re secure to name get() methodology right here.

The final line within the methodology merely checks if the result’s empty then it returns the unique quantity as String in any other case leads to itself.

Our second methodology can be making use of the identical logic but it surely’s a bit of bit extra expressive for Java programmers who’re simply began studying this new approach of coding. On this methodology, the map methodology has precisely the identical logic as our first methodology, however you see we now have diminished plenty of boilerplate code associated to methodology declaration utilizing a lambda expression.

import java.util.Optionally available;

/**
 * FizzBuzz drawback resolution in Java 8. It is a classical drawback to filter
 * programmers who cannot program. Now you should use this to test whether or not your
 * Java candidate is aware of programming with Java 8 Streams or not.
 *
 * Downside : Write a way in Java which is able to return "Fizz" if the quantity is
 * dividable by 3 "Buzz" if the quantity is dividable by 5 "FizzBuzz" if the
 * quantity is dividable by 15 the identical quantity if no different requirement is
 * fulfilled.
 *
 * @writer Javin Paul
 */
public class FizzBuzzJava8 {

    public static void principal(String args[]) {
        System.out.println("FizzBuzz utilizing easy Java : " + fizzBuzz(3));
        System.out.println("FizzBuzz resolution utilizing Java 8  : " 
                                 + fizzBuzzInJava8(15));
    }

    /**
     * Easy Java resolution of FizzBuzz Downside
     *
     * @param quantity
     * @return Fizz if quantity divisible by 3, Buzz if quantity divisible by 5
     * FizzBuzz if divisible by each 3 and 5, or else the identical quantity
     */
    public static String fizzBuzz(int quantity) {
        if (quantity % 15 == 0) {
            return "FizzBuzz";
        } else if (quantity % 3 == 0) {
            return "Fizz";
        } else if (quantity % 5 == 0) {
            return "Buzz";
        }
        return Integer.toString(quantity);
    }

    /**
     * FizzBuzz Resolution utilizing Java 8 Optionally available, map and
     * Stream map() operate is
     * actually helpful right here.
     *
     * @param quantity
     * @return Fizz, Buzz, FizzBuzz or the quantity itself
     */
    public static String fizzBuzzInJava8(int quantity) {
        String outcome = Optionally available.of(quantity)
                .map(n -> (n % 3 == 0 ? "Fizz" : "") 
                               + (n % 5 == 0 ? "Buzz" : ""))
                .get();
        return outcome.isEmpty() ? Integer.toString(quantity) : outcome;
    }

    /*
     * One other Java 8 resolution, this time its little bit extra expressive
     * for Java 8 beginner.
     */
    public static String fizzBuzzSolutionJava8(int enter) {
        return Optionally available.of(enter)
                .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 Check for FizzBuzz drawback

Right here is our set of JUnit assessments to test all three options of Java 8. You may see we now have in whole 4 check circumstances, first to check with numbers that are solely divisible by 3, second to check with a quantity which is divisible by 5, third to check with numbers that are divisible by each 3 and 5 e.g. 15, 30 or 45 and final one with numbers which aren’t divisible by both 3 or 5 e.g. 1 or 2. 

Collectively these 4 strategies cowl all of the necessities of the FizzBuzz drawback.

import org.junit.Assert;
import org.junit.Check;

/**
 * JUnit assessments for our three FizzBuzz resolution, together with two in Java 8. 
 * @writer WINDOWS 8
 */
public class FizzBuzzJava8Test {

    @Check
    public void testWithNumberIsDividableBy3() {
        Assert.assertEquals("Fizz", FizzBuzzJava8.fizzBuzz(3));
        Assert.assertEquals("Fizz", FizzBuzzJava8.fizzBuzzInJava8(3));
        Assert.assertEquals("Fizz", FizzBuzzJava8.fizzBuzzSolutionJava8(3));
    }

    @Check
    public void testWithNumberIsDividableBy5() {
        Assert.assertEquals("Buzz", FizzBuzzJava8.fizzBuzz(5));
        Assert.assertEquals("Buzz", FizzBuzzJava8.fizzBuzzInJava8(5));
        Assert.assertEquals("Buzz", FizzBuzzJava8.fizzBuzzSolutionJava8(5));
    }

    @Check
    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));
    }

    @Check
    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));
    }
}

and right here is the results of our JUnit check. You may see all 4 check circumstances have handed, which suggests all three options are right as per the specification of the fizzbuzz drawback, do not you’re keen on the inexperienced bar?

How to solve FizzBuzz in Java 8 using lambda expression

That is Netbeans’s JUnit run window, you possibly can see it clearly saying all 4 assessments are handed inside 62 milliseconds.

That is all about how you can remedy FizzBuzz in Java 8. As I stated fixing easy programming issues or doing code katas are nice methods to be taught and grasp new options of Java 8, particularly lambda expression and streams. FizzBuzz is likely one of the easiest of the issue however but it teaches us how we are able to deal with Optionally available as stream and use map operate to rework every factor of Optionally available.

Within the coming weeks, we will even see some extra examples of fixing traditional programming issues utilizing Java 8 options. BTW,  If you’re desperate to do it by your self, why not attempt to remedy these 20 String algorithm issues utilizing Java 8 Streams, lambdas, and different options.

In case you like this tutorial and need to be taught extra concerning the new options of Java 8, you’ll love to take a look at these superb articles :

  • High 20 Date and Time Examples of Java 8 (examples)
  • What’s the default methodology in Java 8. (tutorial)
  • Are you prepared for Java 8 Certification? (learn extra)
  • Find out how to use Map operate in Java 8 (instance)
  • 10 Examples of Stream API in Java (examples)
  • Find out how to use Lambda Expression in Place of Nameless class in Java 8 (resolution)
  • 10 Java 7 Function to revisit earlier than you begin with Java 8 (record)
  • 10 Greatest Tutorials to Study Java 8 (record)
  • Find out how to Learn File in Java 8 in a single line? (instance)
  • Find out how to filter Checklist in Java 8 utilizing Predicates? (resolution)
  • What’s the Efficient remaining variable in Java 8? (reply)
  • Java 8 Comparator Instance with Lambdas (instance)
  • Java 8 tutorials and Books for FREE (assets)
  • Find out how to type objects by a number of fields in Java? (comparator instance)

Thanks for studying this text to this point. In case you like this FizzBuzz resolution in Java utilizing map and performance programming then please share them with your pals and colleagues. When you’ve got any
questions or suggestions about this Java 8 tutorial then please drop a word.

P.S. –  If you wish to be taught extra about Java Useful programming ideas like Lambda, Stream, and practical like map, flat map, and filter then please see these finest Java Useful Programming programs. It explains key ideas like lambda expressions,
streams, practical interface, Optionals, and so on.   



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments