我在这里有这个方法从JList获取对象。该对象将是一个匹配hashmap中某些值的字符串。例如,有多个值。根据值显示hashmap的入口集
Course1 - John
Course2 - John
Course3 - Mary
Course4 - Mary
在那里循环任何方式通过一个HashMap,寻找一定的价值,然后将两个键&值成,然后可以添加到列表模式的字符串?
我在这里有这个方法从JList获取对象。该对象将是一个匹配hashmap中某些值的字符串。例如,有多个值。根据值显示hashmap的入口集
Course1 - John
Course2 - John
Course3 - Mary
Course4 - Mary
在那里循环任何方式通过一个HashMap,寻找一定的价值,然后将两个键&值成,然后可以添加到列表模式的字符串?
如果您只是在搜索值,请使用hashmap的keySet()方法获取密钥,然后遍历它们以获取相应的值。
for(String key : hashMap.keySet())
{
String value = hashMap.get(key);
if(searchString.equals(value))
{
String keyAndValue = key + value; // this is what you want
}
}
如果您正在搜索键和值,使用HashMap中的的entrySet()方法,通过它们来获取条目,然后循环来寻找匹配。
for(Map.Entry<String, String> entry : hashMap.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
if(searchString.equals(key) || searchString.equals(value))
{
String keyAndValue = key + value; // this is what you want
}
}
使用其在地图上进行迭代,并返回匹配列表的搜索方法:
public static ArrayList <String> searchMap (HashMap map, String value)
{
ArrayList <String> matchesFound = new ArrayList <String>();
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Map.Entry entry = (Map.Entry) it.next();
if (entry.getValue() == value)
matchesFound.add(entry.getKey() + " : " + entry.getValue());
}
return matchesFound;
}
样品使用与填充HashMap的数据:
public static void main (String [] args)
{
HashMap < String, String > map = new HashMap < String, String >();
map.put("Course1", "John");
map.put("Course2", "John");
map.put("Course3", "Mary");
map.put("Course4", "Mary");
System.out.println(searchMap(map, "Mary"));
}
他想通过搜索** *值***。您刚刚将'get()'重新实现为线性(O(n))搜索。 – 2012-03-03 06:59:19
好的,我会做出改变。我假设他想要根据关键和价值进行搜索。 – CodeBlue 2012-03-03 07:03:02
其实,CodeBlue提供了一个完美的工作代码。你是一个拯救生命的人! – cataschok 2012-03-03 07:04:56