DEV Community

Discussion on: Think twice before using a Supplier

Collapse
 
evanoman profile image
Evan Oman • Edited

Similar to your solution you can compose all of your replace applications together into a single Function<String, String>

private static void populateTemplateFile(Map<String, String> replacementMap)
{
    File file = new File(TEMPLATE_FILE);

    /* Combine all of the replacements into a single function */
    Function<String, String> replacementFunction = replacementMap
            .entrySet()
            .stream()
            .map(kv -> (Function<String, String>) s -> 
                                s.replace(kv.getKey(),kv.getValue()))
            .reduce(Function.identity(), Function::andThen);

    try (Stream<String> lines = Files.lines(Paths.get(file.toURI()));
        PrintWriter output = new PrintWriter(TARGET_FILE, "UTF-8"))
    {
        lines.map(replacementFunction).forEachOrdered(output::println);
    }
    catch (IOException e)
    {
        log.error("Exception while trying to create " + TARGET_FILE,e);
    }
}