wandermonk
wandermonk

Reputation: 7356

What is the efficient and fastest way to check a list of regex pattern on a hashmap in java

I have a hashmap of more than 1000 keys. I have a list of regex patterns. I would like to know the fast and efficient way of searching for all keys matching all patterns from the hashmap to retrieve the Key-Value pairs.

Sample patterns as below

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

Here is the code which I have written but I am iterating the entire map for each pattern.

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

Upvotes: 0

Views: 460

Answers (1)

Bartek Jablonski
Bartek Jablonski

Reputation: 2737

As I understand Your code, You are searching for entries that match to at least one pattern. So I would suggest to invert logic - for each entry check if any pattern matches (applying @elliott-frisch suggestion) - something like this:

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

Upvotes: 1

Related Questions