abc
abc

Reputation: 512

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!

Upvotes: 3

Views: 685

Answers (2)

Andy Turner
Andy Turner

Reputation: 140494

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

Upvotes: 4

Andronicus
Andronicus

Reputation: 26056

Consider using a traditional for loop, since you're changing a global variable:

for(String country: FORMAT) {
    str = str.replaceAll(country + "\\s",  "\\" + simbol);
}

Using Streams in this example will make things less readable.

Upvotes: 2

Related Questions