代码之家  ›  专栏  ›  技术社区  ›  wandermonk

在java中,检查hashmap上的正则表达式模式列表的最有效和最快的方法是什么

  •  0
  • wandermonk  · 技术社区  · 6 年前

    示例模式如下所示

    /Rows/\d{1,}/Mei/des-id
    /Rows/\d{1,}/cona/des-neigr/port-id
    /Rows/\d{1,}/cona/des-neigr/receiving
    

    下面是我编写的代码,但我正在迭代每个模式的整个映射。

    Map<String,String> finalMap = new HashMap<>();
    
            for(String pattern : patternList){
                Pattern p = Pattern.compile(pattern);
                map.entrySet().stream().filter(entry -> p.matcher(entry.getKey()).matches()).forEach(x -> {
                    finalMap.put(x.getKey(),x.getValue().asText());
                });
            }
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Bartek Jablonski    6 年前

    据我所知,您正在搜索至少与一种模式匹配的条目。因此,我建议反转逻辑-对于每个条目检查是否有任何模式匹配(应用@elliott frisch suggestion)-如下所示:

    List<Pattern> patterns = patternList.stream().map(Pattern::compile).collect(Collectors.toList());
    Map<String, String> finalMap = map.entrySet().stream()
            .filter(
                    entry -> patterns.stream()
                            .anyMatch(
                                    pattern -> pattern.matcher(entry.getKey()).matches()
                            )
            )
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    entry -> entry.getValue().asText()
            ));