Fizzbuzz in Java sweetened by Kotlin
Sharan Salian
1262

You have an interesting definition of readable… You could use the same Map hack in Java too with some extra functions instead of just the if-else, it would still be messy. In Kotlin, I think you’d just need to do this:

(0..100).forEach { i ->
println(when {
i % 3 == 0 && i % 5 == 0 -> "FizzBuzz"
i % 5 == 0 -> "Buzz"
i % 3 == 0 -> "Fizz"
else
-> "$i"
})
}

Which is the same as the Java version, except actually more readable. ;)

— — — — — — — —

For sake of completion, here is your Java equivalent for your Kotlin version:

private class MapBuilder<K, V> {
List<Map.Entry<K, V>> list = new ArrayList<>();

public MapBuilder<K, V> put(K key, V value) {
list.add(new AbstractMap.SimpleEntry<>(key, value));
return this;
}

public Map<K, V> build() {
Map<K, V> map = new HashMap<>();
for(Map.Entry<K, V> entry: list) {
map.put(entry.getKey(), entry.getValue());
}
return Collections.unmodifiableMap(map);
}
}

private <K, V> MapBuilder<K, V> mapBuilder() {
return new MapBuilder<>();
}

@Test
public void javaFizz() {
for(int i = 0; i <= 100; i++) {
System.out.println(this.<Integer, String>mapBuilder()
.put(0, String.valueOf(i))
.put(i % 3, "Fizz")
.put(i % 5, "Buzz")
.put(i % 15, "FizzBuzz")
.build().get(0));
}
}

It’s not as memory efficient as the original Java version.