How to write a lambda expression when you are using a string array?

abc :

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!

Andy Turner :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374388&siteId=1