[英]transform xml string by lambda java8
I have String
as XML. 我有
String
作为XML。 I'm trying to transform String
by regexp: 我正在尝试通过正则表达式转换
String
:
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: 并使用map替换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
)? 如何在不保存数组的情况下编写lambda表达式(lambda使用
String
,通过map转换并返回String
)?
You can use reduce
to apply all the elements of the Stream
of map entries on your template
String. 您可以使用
reduce
将template
条目Stream
的所有元素应用于template
字符串。
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: 不过,我不确定合并
combiner
外观(即如何将两个部分转换的String
合并为包含所有转换的String
),但是如果顺序Stream
足够,则不需要合并器:
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: 除了使用中间映射,您可以直接应用终端操作,而使用@red建议的.reduce
.reduce()
操作:
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. 这样,您将没有太多的开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.