I am trying to code a FizzBuzz issue in Java8. It works fine, and I get the desired result. For a number divisible by “3,” it should return “Fizz,” for a number divisible by “5,” it should return “Buzz,” and for a number divisible by both, it should return “FizzBuzz.”
If I pass the value as "15", it returns:
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Now I'm stuck in one. I want to get the output as follows, if I pass the value "15":
{"Fizz": [3, 6, 9, 12],"Buzz": [5, 10],"FizzBuzz": [15]}
I want to group numbers using Fizz, Buzz and FizzBuzz.
Here is my code:
public class FizzBuzzService {
private Map<Rule, String> ruleContainers = new HashMap();
private Set<Rule> rules = new HashSet();
public FizzBuzzService(){
addRule(i -> i % 15 == 0, "FizzBuzz");
addRule(i -> i % 3 == 0, "Fizz");
addRule(i -> i % 5 == 0, "Buzz");
}
public void addRule(Rule rule, String res) {
rules.add(rule);
ruleContainers.put(rule, res);
}
public String getValue(int i) {
for (Rule rule : rules) {
if (rule.apply(i)) {
return ruleContainers.get(rule);
}
}
return String.valueOf(i);
}
public List<String> fizzBuzz(int n) {
List<String> res = new ArrayList();
for(int i = 1; i <= n; i++){
res.add(getValue(i));
}
return res;
}
interface Rule{
boolean apply(int i);
}
}
I would really appreciate it if anyone could guide me. Thanks