Java 8 Stream - 如何返回用要查找的项列表替换字符串内容 [英] Java 8 Stream - How to return replace a strings contents with a list of items to find

查看:1177
本文介绍了Java 8 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"

这篇关于Java 8 Stream - 如何返回用要查找的项列表替换字符串内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆