所以,我正在编写一些java。并且想要搜索一个HashMap然后循环结果,这是我的HashMap:
public HashMap<String, String> messages;
但是!我不想循环所有的键,只是一些。就像搜索MySQL数据库一样。
对不起我的英语,我是挪威人。
如果我理解正确,您希望遍历HashMap的键。为此,您需要使用Map.keySet()方法。这将返回一个集合,其中包含地图的所有关键点。或者,您可以遍历entrySet或值。(请查看提供的所有链接以了解更多详细信息。)
此外,我强烈建议您查看集合教程。您还应该熟悉Java API文档。特别是,您需要查看HashMap和Map的文档。
在Block
类中正确实现equals
hashcode
,并在Hashmap
上调用get(Object key)
方法,它将进行搜索。
如果您想访问所有键并获取值。
public HashMap<String, String> messages;
...
for (final String key : messages.keySet()) {
final String value = messages.get(key);
// Use the value and do processing
}
一个更好的想法是只使用messages.entrySet
。。。
for (final Map.Entry<String, String> entry : messages.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
}
仍然很不清楚,但您询问了如何同时执行entrySet()和entryKey()。然而,entrySet()在一个数据结构中同时返回Key和Value:
for( Map.Entry<String,String> entry : messages.entrySet() ) {
String key = entry.getKey();
String value = entry.getValue();
System.out.printf("%s = %s%n", key, value );
}
但通常情况下,你不会这样做,而是简单地使用Key来获得Value,这样就产生了一种更简单的迭代方法:
for( String key : messages.keySet() ) {
String value = messages.get(key);
System.out.printf("%s = %s%n", key, value );
}
不存在只使用默认Java中包含的工具来"查询"MySQL这样的地图的设施。像apache集合这样的库提供谓词和其他过滤器,可以为您提供查询支持。其他图书馆包括番石榴图书馆。例如,使用apachecommons集合:
List<String> keys = new ArrayList<String>(messages.keySet());
CollectionUtils.filter( keys, new Predicate<String>() {
public boolean evaluate( String key ) {
if( someQueryLogic ) {
return true;
} else {
return false;
}
}
} );
// now iterate over the keys you just filtered
for( String key : keys ) {
String value = message.get(key);
System.out.printf("%s = %s%n", key, value );
}