ABC:
私は古典のためにするのではなく、ラムダ式を使用します。
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
任意の文字列のために、私は$ simbolでUSDまたはCADを変更したいです。
どのように私は仕事にこのコードを変更することができますか?前もって感謝します!
アンディ・ターナー:
私はこのためにループを使用しても問題は見られません。それは私がおそらくそれを行うだろう方法です。
あなたは使ってストリームでそれを行うことができますreduce
。
str = Arrays.stream(FORMAT)
.reduce(
str,
(s, country) -> s.replaceAll(country + "\\s", Matcher.quoteReplacement(simbol)));
または、簡単に:
str = str.replaceAll(
Arrays.stream(FORMAT).collect(joining("|", "(", ")")) + "\\s",
Matcher.quoteReplacement(simbol));