We help IT Professionals succeed at work.

hashmap find by like

komputer asked

i would like to use searh in hashmap (or similar with it) with like operator ('%') like in sql.
how can i do?

imagine i have a map like that;
1000, a1
1001, a2
2000, b1
2001, b2

what i need it when i run like this map.get(10%), it will give an array of object that contains a1, a2

thanks in advance.

Watch Question

The only way I can think of of the top of my head is to implement your own Map class. Possibliy just extending HashMap. You then need to override the get method so that it searches the key set for keys that match your wildcard pattern. Let me know if you want details...


i need a solution, an open-source lib or source code.
I don't know of any open-source lib for this and some code snippets is what I can give you here. Take it or leave it ;-)

On second thought, I'd rather use a Utility class for this than subclassing HashMap. Most projects have some sort of CollectionUtil that I'm sure you can put it in. This example is by no means optimized for big amounts of data and the example uses regular expression matching instead of '%' syntax (you'll have to write the matches method yourself for that):

public static List wildcardGet(String key, Map map) {
	List retList = new ArrayList();
	String sKey = (String) key;
	Set keys = map.keySet();
	for (Iterator iter = keys.iterator(); iter.hasNext();) {
		Object o = (Object) iter.next();
		if (o instanceof String) {
			if (matches(key, (String) o)) {
	return retList;
private static boolean matches(String matchString, String target) {
	return target.matches(matchString);

Open in new window

Ooops, the cast to sKey is unnecessary of course.

Usage is:

List l = CollectionUtil.wildcardGet("10\\w*", myMap);

What kind of objects are a1, a2


alhough it not what i look for (since it iterates all object and this will cause performance problems), i will accept, cause i have not found a geniric solution.

thanks guys.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.