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

2022-01-22 00:00:00 foreach java-8 java java-stream

我希望使用 java8 .stream() 替换下面的代码或 .foreach().但是我在执行此操作时遇到了麻烦.

I wish to replace the code below using java8 .stream() or .foreach(). However I am having trouble doing this.

这可能很容易,但我正在寻找一种思考斗争的实用方法:)

Its probably very easy, but I'm finding the functional way of thinking a struggle :)

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

I can iterate, no problem but the but returning the modified string is the issue due to mutability issues.

有人有什么想法吗?

List<String> toRemove = Arrays.asList("1", "2", "3");
String text = "Hello 1 2 3";

for(String item : toRemove){
    text = text.replaceAll(item,EMPTY);
}

谢谢!

推荐答案

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

Wow, you guys like doing things the hard way. this is what filter() and collect() are for.

List<String> 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 + """);

输出(与原始代码一样)

outputs (as the original code did)

"Hello   "

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

Of course, if your search strings are longer than one character, the previous method works better. If you have a tokenized string, though, split and join is easier.

List<String> 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"

相关文章