public String pickOne(int input) {
if ((input % 15) == 0) {
return "fizzbuzz";
} else if ((input % 3) == 0) {
return "fizz";
} else if((input % 5) == 0) {
return "buzz";
}
return String.valueOf(input);
}
Constructing the string from pieces
You can reduce one if by removing "else" conditions. Downside is, that you need to add another if
in the end for the return values so probably not better, but should be mentioned:
public String pickOneV2(int input) {
var sb = new StringBuilder();
if (input % 3 == 0) {
sb.append("fizz");
}
if (input % 5 == 0) {
sb.append("buzz");
}
if (sb.length() == 0) {
return String.valueOf(input);
}
return sb.toString();
}
public String pickOneV2pickOneV3(int input) {
var fizzbuzzMap = new TreeMap<Integer, String>(Comparator.reverseOrder());
fizzbuzzMap.put(3, "fizz");
fizzbuzzMap.put(5, "buzz");
fizzbuzzMap.put(15, "fizzbuzz");
for (var index : fizzbuzzMap.keySet()) {
if (input % index == 0) {
return fizzbuzzMap.get(index);
}
}
return String.valueOf(input);
}
public String pickOneV2pickOneV4(int input) {
var fizzbuzzMap = new TreeMap<Integer, String>(Comparator.reverseOrder());
fizzbuzzMap.put(3, "fizz");
fizzbuzzMap.put(5, "buzz");
fizzbuzzMap.put(15, "fizzbuzz");
return fizzbuzzMap.entrySet().stream().filter(
entry -> input % entry.getKey() == 0
).map(Map.Entry::getValue).findFirst().orElse(String.valueOf(input));
}