【发布时间】:2013-10-01 02:51:12
【问题描述】:
我有一个HashMap<Integer,String>。我尝试了以下代码来查询地图并返回所有可能的值
public Collection<String> query(String queryStr) {
List<String> list = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
if (queryStr.matches(entry.getKey()))
list.add(entry.getKey());
}
if (list.isEmpty())
return null;
else
return list;
}
如果地图有"test","best","crest","zest","testy","tether","temper","teat","tempest"。 te*t 的查询应返回 "teat","tempest","test"。对于“test*”,它应该返回“test”、“testy”。如何实施?是否有任何通配符搜索字符串?而且我不能使用任何外部库。
【问题讨论】:
-
String有方法matches。您还可以使用Pattern和Matcher类。 -
如果列表为空,为什么返回 null?只返回一个空列表会更有意义。
-
assertArrayEquals(new Object[] {"best","crest","tempest","test","zest"}, getSortedArray(dict.query("*est") ));没有返回任何东西。
-
@arshajii 它是测试用例的要求。我无法更改它们。
标签: java collections wildcard