从java中的HashMap返回通配符匹配列表 [英] Returning a list of wildcard matches from a HashMap in java

查看:110
本文介绍了从java中的HashMap返回通配符匹配列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashMap,它可以在字符串中包含通配符(*)。



例如,

  HashMap< String,Student>学生们_; 

可以将John *作为一个键。我想知道JohnSmith是否与students_中的任何元素相匹配。可能有几个匹配我的字符串(约翰*,乔*史密斯等)。有什么办法可以从我的HashMap中获得这些匹配的列表吗?

是否有另一个对象可以使用,它不需要我迭代我的集合中的每个元素,还是必须将其吸收并使用List对象?



仅供参考,我的收藏中包含的元素少于200个,最终我希望找到与最少量的通配符匹配的配对。

解决方案

由于hashing函数,使用hasmap无法实现。它必须分配John *的散列和John Smith等的散列。如果你写自己的自定义类 WildcardString wrapping String可以使用TreeMap来创建它。

,并以John *。compareTo(John Smith)返回0来实现 compareTo 。你可以用正则表达式来做到这一点,比如其他答案已经指出。



看到您想要widlcard匹配列表,您可以随时删除条目你可以找到它们,并迭代 TreeMap.get()的。请记住在完成名称后放回钥匙。



这只是实现它的一种可能方式。


$ b 更新:正确地在 TreeSet ,您可以区分比较两个 WildcardString s(意味着它是键之间的比较)并比较 WildcardString 转换为字符串(将键与搜索值进行比较)。

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

For instance,

HashMap<String, Student> students_;

can have John* as one key. I want to know if JohnSmith matches any elements in students_. There could be several matches for my string (John*, Jo*Smith, etc). Is there any way I can get a list of these matches from my HashMap?

Is there another object I could be using that does not require me to iterate through every element in my collection, or do I have to suck it up and use a List object?

FYI, my collection will have less than 200 elements in it, and ultimately I will want to find the pair that matches with the least amount of wildcards.

解决方案

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).

这篇关于从java中的HashMap返回通配符匹配列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆