hashmap find by like

hi,

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.


 
komputerAsked:
Who is Participating?
 
schybertConnect With a Mentor Commented:
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)) {
				retList.add(map.get(o));
			}
		}
	}
 
	return retList;
}
 
private static boolean matches(String matchString, String target) {
	return target.matches(matchString);
}

Open in new window

0
 
schybertCommented:
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...
0
 
komputerAuthor Commented:
i need a solution, an open-source lib or source code.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
schybertCommented:
Ooops, the cast to sKey is unnecessary of course.

Usage is:

List l = CollectionUtil.wildcardGet("10\\w*", myMap);
0
 
cmalakarCommented:
What kind of objects are a1, a2
0
 
komputerAuthor Commented:
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.
0
All Courses

From novice to tech pro — start learning today.