How can I format a string with streams, without using lambda? I've been looking at Formatter
but can't find any method that would only take a single string... so I could do:
Set<String> imported = new HashSet<>();
extendedModels.stream().filter((x)->imported.add(x))
.map(new Formatter("import {%1$s} from './%1$s';\n")::format);
I'm just starting with Java 8 so not sure if the above is a right syntax (referencing a method of an object).
Specifically I look for a way to format the strings without the lambda expression. The reason is brevity - because, the pre-Java 8 form is just:
for (String m : extendedModels)
if (imported.add(m))
tsWriter.write(String.format("import {%1$s} from './%1$s';\n", m));
Details not related to the question:
I'm trying to go through a list of strings, reduce them to unique*) ones, and then use them in an formatted string, which will ultimately written to a Writer
. Here's what I have now:
This would work but I'd have to handle an IOException
in forEach
:
extendedModels.stream().filter(imported::add)
.map((x)->{return String.format("import {%1$s} from './%1$s';\n", x);})
.forEach(tsWriter::write);
So for now I use this:
tsWriter.write(
extendedModels.stream()
.filter(imported::add)
.map((x)->{return String.format("import {%1$s} from './%1$s';\n", x);})
.collect(Collectors.joining())
);
*) The uniqueness is across multiple sets, not just the extendedModels
so I don't want to use some sort of unique
stream util.