在 java8 中使用列表中的项目更新字符串



我有一个字符串,想根据列表内容更改字符串。

List<String> lst = new ArrayList<>();
       lst.add("</lldp>");
       lst.add("</ftp>");
       lst.add("</snmp>");
       String text2 = "The cefcFRURemoved notification </snmp>";
       for(String str: lst) {
           text2 = text2.replaceAll(str, "");
       }

我想找到一种等效的方法,使用 java8 流做同样的事情。

**Something like : tagList.stream().map((e) ->  text.replaceAll(e, "")).collect(Collectors.joining())** 

当然,这是完全错误的做法。但我正在尝试找到流方法来做同样的事情

String p = lst.stream()
              .map(Pattern::quote)
              .collect(Collectors.joining("|"));
String text2 = "The cefcFRURemoved notification </snmp>";
System.out.println(text2.replaceAll(p, ""));

或者你可以连接你关心的所有模式,简单地做一个replaceAll

也许用这个代替流:

text2 = text2.replaceAll(String.join("|", lst), "");
    final List<String> lst = Arrays.asList("</lldp>", "</ftp>", "</snmp>");
    final String text2 = "The cefcFRURemoved notification </snmp>";
    /*
     * sequential() is important here. If you run in parallel() instead,
     * the code will fail.
     */
    final String result = lst.stream().sequential()
                             .map(Pattern::quote)
                             .map(Pattern::compile)
                             .reduce(text2,
                                     (input, pattern) -> pattern.matcher(input).replaceAll(""),
                                     (left, right) -> {
                                         /*
                                          * Never invoked for sequential streams.
                                          */
                                         throw new UnsupportedOperationException(String.format("left="%s"; right="%s"", left, right));
                                     });
    System.out.println(result);

最新更新