【问题标题】:How to write a lambda expression when you are using a string array?使用字符串数组时如何编写 lambda 表达式?
【发布时间】:2020-03-31 09:52:48
【问题描述】:

我想使用 lambda 表达式而不是经典的 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

对于任何字符串,我想在 $ simbol 中更改 USD 或 CAD。
如何更改此代码以使其正常工作?提前致谢!

【问题讨论】:

  • 使用Matcher.quoteReplacement(simbol) 而不是"\\" + simbol
  • 但是,正如 Andronicus 在下面的答案中指出的那样,您的原始循环是正确的方法。
  • 预期输出是什么?
  • 您想使用 streams,而不是 lambda 表达式。

标签: java arrays regex lambda java-8


【解决方案1】:

我认为为此使用循环没有问题。这就是我可能会这样做的方式。

您可以使用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));

【讨论】:

  • 除了主要问题country + "\\s 应该是country + "\\b(单词边界),否则USD. 不会被替换,因为USD 后面没有空格。
  • @Pshemo 当然;但我们也许还应该指出,你写的不是“30$”,而是“$30”。总体而言,这并不是一个好方法。
  • "你写的不是“30$”,而是“$30””哦,今天学到了,谢谢。
  • reduce 变体违反了关联性约束。正则表达式变体仅对最后一种格式强制使用尾随空格。您需要"("+String.join("|", FORMAT)+")\\s"String.join("\\s|", FORMAT)+"\\s" 来强制每个变体后面都需要一个空格。
  • collect 之后不需要再连接字符串,只需使用joining("|", "(", ")\\s")
【解决方案2】:

考虑使用传统的 for 循环,因为您要更改全局变量:

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

在这个例子中使用Streams 会降低可读性。

【讨论】:

  • OP不就是这样开始的吗?
  • @Pshemo 对,我误读了这个问题,最后得到了这个答案,因为我达到了限制,我无法删除它,必须想出其他解决方案;>
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多