Map

Raindrops
Raindrops in Java
import java.util.Map;
import java.util.TreeMap;

class RaindropConverter {
    private static final TreeMap < Integer, String > lookup = new TreeMap < Integer, String > (
        Map.of(3, "Pling", 5, "Plang", 7, "Plong"));
        
    String convert(int number) {
        var output = new StringBuilder("");
        lookup.forEach((divisor, drop) -> {
            if (number % divisor == 0)
                output.append(drop);
        });
        return output.length() != 0 ? output.toString() : Integer.toString(number);
    }
}

This approach begins by importing Map and TreeMap.

A private static final TreeMap is defined for efficient sorting of keys. It is private because it doesn't need to be seen outside the class. It is static because it doesn't need to differ between object instantiations, so it can belong to the class itself. It is final because it does not need to be changed after it is created. The Map.of() method is used to populate the map.

A StringBuilder is defined to build the result String.

The forEach() method is used to iterate the map entries. The remainder operator is used to check if the number is evenly divisible by the key of the map entry. If so, the value of the map entry is appended by the StringBuilder.

After the forEach() is done, a ternary operator is used to check the StringBuilder.length(). If it is not 0, then the StringBuilder.toString() method is called and its value is returned. If the length is 0, then the number is converted to a string using Integer.toString() and is returned.

The use of StringBuilder may not be as performant for so few appends, due to the time it takes to instantiate the StringBuilder. Other ways of building the result may be faster.

27th Nov 2024 · Found it useful?