I have String
as XML. I'm trying to transform String
by regexp:
public String replaceValueByTag(final String source, String tag, String value) {
return replaceFirst(source, "(?<=<" + tag + ">).*?(?=</" + tag + ">)", value);
}
then create map with tag, new value:
Map<String, String> params = TAGS.stream().collect(toMap(tag -> tag, tag -> substringByTag(request, tag)));
and use map to replace values in XML:
public String getConfirm(String request) {
String[] answer = {template};
Map<String, String> params = TAGS.stream().collect(toMap(tag -> tag, tag -> substringByTag(request, tag)));
params.entrySet().forEach(entry -> answer[0] = replaceValueByTag(answer[0], entry.getKey(), entry.getValue()));
return answer[0];
}
How to write lambda expression without saving in array (lambda takes String
, converts it by map and returns a String
)?
You can use reduce
to apply all the elements of the Stream
of map entries on your template
String.
I'm not sure, though, how the combiner
should look like (ie how to combine two partially transformed String
s into a String
that contains all transformations), but if a sequential Stream
is sufficient, you don't need the combiner:
String result =
params.entrySet()
.stream()
.reduce(template,
(t,e) -> replaceValueByTag(t, e.getKey(), e.getValue()),
(s1,s2)->s1); // dummy combiner
instead of using an intermediate map you could directly apply the terminal operation, I'll use the .reduce()
operation like @Eran suggested:
String result = TAGS.stream()
.reduce(
template,
(tmpl, tag) -> replaceValueByTag(tmpl, tag, substringByTag(request, tag),
(left, right) -> left) // TODO: combine them
);
This way you wont have as much overhead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.