我需要将正则表达式列表应用到字符串,所以我想使用java8 map reduce:
List<SimpleEntry<String, String>> list = new ArrayList<>();
list.add(new SimpleEntry<>("\\s*\\bper\\s+.*$", ""));
list.add(new SimpleEntry<>("\\s*\\bda\\s+.*$", ""));
list.add(new SimpleEntry<>("\\s*\\bcon\\s+.*$", ""));
String s = "Tavolo da cucina";
String reduced = list.stream()
.reduce(s, (v, entry) -> v.replaceAll(entry.getKey(), entry.getValue()) , (c, d) -> c);
实际上这段代码可能不是很漂亮,但是它可以工作。我知道这不能并行,但对我来说没问题。
现在我的问题是:Java8(或更高版本)是否有机会编写更优雅的东西?我的意思是还要避免添加无用的组合器功能。
最佳答案
受到 Oleksandr 的评论和 Holger 的启发,我写了这篇文章
String reduced = list.stream()
.map(entry->
(Function<String, String>) v -> v.replaceAll(entry.getKey(), entry.getValue()))
.reduce(Function.identity(), Function::andThen)
.apply(s);
这也减少了函数组合的所有条目。
关于java8 用无用的组合器来减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50639966/