Returning a list of wildcard matches from a HashMap in java

前端 未结 3 731
不思量自难忘°
不思量自难忘° 2021-01-04 14:25

I have a Hashmap which may contain wildcards (*) in the String.

For instance,

HashMap students_;

can have

3条回答
  •  佛祖请我去吃肉
    2021-01-04 14:52

    It's not possible to achieve with a hasmap, because of the hashing function. It would have to assign the hash of "John*" and the hash of "John Smith" et al. the same value.

    You could make it with a TreeMap, if you write your own custom class WildcardString wrapping String, and implement compareTo in such a way that "John*".compareTo("John Smith") returns 0. You could do this with regular expressions like other answers have already pointed out.

    Seeing that you want the list of widlcard matchings you could always remove entries as you find them, and iterate TreeMap.get()'s. Remember to put the keys back once finished with a name.

    This is just a possible way to achieve it. With less than 200 elements you'll be fine iterating.

    UPDATE: To impose order correctly on the TreeSet, you could differentiate the case of comparing two WildcardStrings (meaning it's a comparation between keys) and comparing a WildcardString to a String (comparing a key with a search value).

提交回复
热议问题