我有1000多个钥匙的哈希图。我有一个正则表达式的列表。我想知道如何快速有效地搜索所有匹配hashmap中所有模式的键,以检索键值对。
样本模式如下
/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());
});
}发布于 2019-09-23 08:37:08
正如我理解您的代码一样,您正在搜索与至少一个模式匹配的条目。因此,我建议反转逻辑--对于每个条目检查是否有任何模式匹配(应用@elliott建议)--如下所示:
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()
));https://stackoverflow.com/questions/58056793
复制相似问题