Java 8 Stream - How to return replace a strings contents with a list of items to find(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 - 如何返回用要查找的项目列表替换字符串内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 Stream - 如何返回用要查找的项目列表替换字符串内容
基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
