あなたは文字列の配列を使用しているとき、どのようにラムダ式を書くには?

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));

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=374897&siteId=1