Search code examples
javajava-streamfizzbuzz

Using IntStream to iterate and call a method


How can I call a function to print a value while iterating over a range using an IntStream?

public static void fizzBuzz(int n) {

    // The below does not work as it expects a return value.
    // Is there a different method that I could use to perform this?
    IntStream.range(1, n).map(n -> print(n));
}

private static void print(int n){
    boolean isDivisibleBy3 = n % 3 == 0;
    boolean isDivisibleBy5 = n % 5 == 0;
    
    if(isDivisibleBy3 && isDivisibleBy5){
        System.out.println("FizzBuzz");
    } else if (isDivisibleBy3){
        System.out.println("Fizz");
    } else if (isDivisibleBy5){
        System.out.println("Buzz");
    } else {
        System.out.println(n);
    }
}

Solution

  • Perhaps this is what you wanted. Have the method return the string. Then use IntStream to iterate thru the numbers. These are then passed on to the method which maps an int to the returned value which is a String. Then you simply print that value.

    public class FizzBuzzStream {
        
        public static void main(String[] args) {
            
            int n = 20;
            
            IntStream.range(1, n).mapToObj(FizzBuzzStream::eval)
                    .forEach(System.out::println); 
            
        }
        
        private static String eval(int n) {
            boolean isDivisibleBy3 = n % 3 == 0;
            boolean isDivisibleBy5 = n % 5 == 0;
            
            if (isDivisibleBy3 && isDivisibleBy5) {
                return "FizzBuzz";
            }
            if (isDivisibleBy3) {
                return "Fizz";
            }
            if (isDivisibleBy5) {
                return "Buzz";
            }
            return Integer.toString(n);
        }
        
    }
    

    Prints

    1
    2
    Fizz
    4
    Buzz
    Fizz
    7
    8
    Fizz
    Buzz
    11
    Fizz
    13
    14
    FizzBuzz
    16
    17
    Fizz
    19