可能的重复:
如何在地图中的每个条目上迭代?
我有一张地图, Map<String, Records> map = new HashMap<String, Records> ();
public class Records
{
String countryName;
long numberOfDays;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getNumberOfDays() {
return numberOfDays;
}
public void setNumberOfDays(long numberOfDays) {
this.numberOfDays = numberOfDays;
}
public Records(long days,String cName)
{
numberOfDays=days;
countryName=cName;
}
public Records()
{
this.countryName=countryName;
this.numberOfDays=numberOfDays;
}
我已经实施了地图的方法,现在请告诉我如何访问hashmap中存在的所有值。我需要在Android的UI上显示它们?
您可以使用loop
来做到这一点Set keys = map.keySet(); // It will return you all the keys in Map in the form of the Set
for (Iterator i = keys.iterator(); i.hasNext();)
{
String key = (String) i.next();
Records value = (Records) map.get(key); // Here is an Individual Record in your HashMap
}
您可以使用Map#entrySet
方法,如果要访问keys
和values
,则可以从HashMap
中拒绝: -
Map<String, Records> map = new HashMap<String, Records> ();
//Populate HashMap
for(Map.Entry<String, Record> entry: map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
另外,您可以在Record
类中覆盖toString
方法,以在for-each
循环中打印instances
的字符串表示。
更新: -
如果您想根据key
按字母顺序排序Map
,则可以将Map
转换为TreeMap
。它将自动放入按键排序的条目: -
Map<String, Integer> treeMap = new TreeMap<String, Integer>(map);
for(Map.Entry<String, Integer> entry: treeMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
有关更详细的说明,请参阅此帖子: - 如何按java中的键对映射值进行分类
如果您准备好使用HashMap
数据,则只需迭代HashMap
键即可。只需一个一个一个迭代和获取数据。
检查以下内容:通过hashmap
map.values()
为您提供了Collection
,并在您的HashMap
中所有值。