Java 8 Stream – 如何返回用要查找的项列表替换字符串内容

我希望使用java8 .stream()或.foreach()替换下面的代码。 但是我这样做有困难。

它可能很容易,但我找到了思考斗争的function方式:)

我可以迭代,没问题,但由于可变性问题而返回修改后的字符串是问题。

有人有主意吗 ?

List toRemove = Arrays.asList("1", "2", "3"); String text = "Hello 1 2 3"; for(String item : toRemove){ text = text.replaceAll(item,EMPTY); } 

谢谢 !

哇,你们喜欢用艰难的方式做事。 这就是filter()和collect()的用途。

 List toRemove = Arrays.asList("1", "2", "3"); String text = "Hello 1 2 3"; text = Pattern.compile("").splitAsStream(text) .filter(s -> !toRemove.contains(s)) .collect(Collectors.joining()); System.out.println("\"" + text + "\""); 

输出(如原始代码所做)

 "Hello " 

当然,如果搜索字符串长于一个字符,则前一种方法效果更好。 但是,如果您有一个标记化的字符串,则拆分和连接更容易。

 List toRemove = Arrays.asList("12", "23", "34"); String text = "Hello 12 23 34 55"; String delimiter = " "; text = Pattern.compile(delimiter).splitAsStream(text) .filter(s -> !toRemove.contains(s)) .collect(Collectors.joining(delimiter)); System.out.println("\"" + text + "\""); 

输出

 "Hello 55" 

由于您无法使用流来修改text变量,因此必须将操作强制转换为一个Function ,您可以将该Function应用于text以获得最终结果:

 List toRemove = Arrays.asList("1", "2", "3"); String text = "Hello 1 2 3"; text=toRemove.stream() .map(toRem-> (Function)s->s.replaceAll(toRem, "")) .reduce(Function.identity(), Function::andThen) .apply(text); 
 text = toRemove.stream() .reduce(text, (str, toRem) -> str.replaceAll(toRem, "")); 

会对你有用。

如果我理解正确,你想做这样的事情:

 toRemove.forEach(removeString -> { text = text.replaceAll(removeString, ""); }); 

唯一的问题是,你做不到。 🙁

你可以在这里阅读: http : //javarevisited.blogspot.co.il/2014/02/10-example-of-lambda-expressions-in-java8.html

第6节: One restriction with lambda expression is that, you can only reference either final or effectively final local variables, which means you cannot modified a variable declared in the outer scope inside a lambda.

编辑

你可以做一些非常丑陋的事情。 喜欢这个:

 private static String text; public void main (String[] args) { text = "Hello 1 2 3"; List toRemove = Arrays.asList("1", "2", "3"); toRemove.forEach(removeString -> replaceTextWithEmptyString(removeString)); } private static void replaceTextWithEmptyString(String whatToReplace) { text = text.replaceAll(whatToReplace, ""); }