java - How to write a lambda expression when you are using a string array?
问题描述
I want to use a lambda expression instead of a classic for.
String str = "Hello, Maria has 30 USD.";
String[] FORMAT = {"USD", "CAD"};
final String simbol = "$";
// This was the initial implementation.
// for (String s: FORMAT) {
// str = str.replaceAll(s + "\\s", "\\" + FORMAT);
// }
Arrays.stream(FORMAT).forEach(country -> {
str = str.replaceAll(country + "\\s", "\\" + simbol);
});
// and I tried to do like that, but I receiced an error
// "Variable used in lambda expression should be final or effectively final"
// but I don't want the str String to be final
For any string, I want to change the USD or CAD in $ simbol.
How can I changed this code to work ? Thanks in advance!
解决方案
I see no problem with using a loop for this. That's how I'd likely do it.
You can do it with a stream using reduce
:
str = Arrays.stream(FORMAT)
.reduce(
str,
(s, country) -> s.replaceAll(country + "\\s", Matcher.quoteReplacement(simbol)));
Or, easier:
str = str.replaceAll(
Arrays.stream(FORMAT).collect(joining("|", "(", ")")) + "\\s",
Matcher.quoteReplacement(simbol));
推荐阅读
- python - 向 nifti 文件添加维度
- ios - swift_getSingletonMetadata 中的 Swift 崩溃,“类型元数据访问器”
- youtube-api - YouTube 中显示的评论与实际评论列表之间的差异
- java - 为什么我的 Spring Batch 多线程步骤在任何处理之前执行所有读取?
- excel - 将编码放入 ListObject 表中
- javascript - nodejs + express 从数据库加载上下文配置
- javascript - 将对象的每个道具转换为对象数组
- java - 如何检查 Java 是否使用配置的代理服务器?
- javascript - 使用 NodeJS 更改 HTML 显示的文本
- javascript - 当我使用 javascript 加载图像时,$_FILES 为空