Over a million developers have joined DZone.

A Regular Expression HashMap Implementation in Java

· Java Zone

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

Below is an implementation of a Regular Expression HashMap. It works with key-value pairs which the key is a regular expression. It compiles the key (regular expression) while adding (i.e. putting), so there is no compile time while getting. Once getting an element, you don't give regular expression; you give any possible value of a regular expression. 

As a result, this behaviour provides to map numerous values of a regular expression into the same value. The class does not depend to any external libraries, uses only default java.util. So, it will be used simply when a behaviour like that is required.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Pattern;
 * This class is an extended version of Java HashMap
 * and includes pattern-value lists which are used to
 * evaluate regular expression values. If given item
 * is a regular expression, it is saved in regexp lists.
 * If requested item matches with a regular expression,
 * its value is get from regexp lists.
 * @author cb
 * @param <K> : Key of the map item.
 * @param <V> : Value of the map item.
public class RegExHashMap<K, V> extends HashMap<K, V> {
    // list of regular expression patterns
    private ArrayList<Pattern> regExPatterns = new ArrayList<Pattern>();
    // list of regular expression values which match patterns
    private ArrayList<V> regExValues = new ArrayList<V>();
     * Compile regular expression and add it to the regexp list as key.
    public V put(K key, V value) {
        return value;
     * If requested value matches with a regular expression,
     * returns it from regexp lists.
    public V get(Object key) {
        CharSequence cs = new String(key.toString());
        for (int i = 0; i < regExPatterns.size(); i++) {
            if (regExPatterns.get(i).matcher(cs).matches()) {
                return regExValues.get(i);
        return super.get(key);



The Java Zone is brought to you in partnership with JetBrains.  Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.


Published at DZone with permission of Cagdas Basaraner , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}