黑马程序员技术交流社区
标题:
Java中HashMap的方法entrySet和keySet遍历元素
[打印本页]
作者:
ifuzhen
时间:
2014-4-15 01:44
标题:
Java中HashMap的方法entrySet和keySet遍历元素
/*
Map集合被使用是因为具备映射关系。
*/
import java.util.*;
class Province
{
private int id;
private String name;
Province(int id,String name)
{
this.id =id;
this.name =name;
}
public String getInfo()
{
return id+":::"+name;
}
}
class Test
{
public static void main(String [] args)
{
HashMap<Integer,List<Province>> hm =new HashMap<Integer,List<Province>>();
List<Province> CHN =new ArrayList<Province>();
List<Province> USA =new ArrayList<Province>();
List<Province> ENG =new ArrayList<Province>();
hm.put(1,CHN);
hm.put(2,USA);
hm.put(3,ENG);
CHN.add(new Province(1,"cd"));
CHN.add(new Province(2,"cs"));
CHN.add(new Province(3,"cj"));
USA.add(new Province(2,"us"));
USA.add(new Province(3,"ub"));
USA.add(new Province(1,"ua"));
ENG.add(new Province(3,"ee"));
ENG.add(new Province(1,"ea"));
ENG.add(new Province(2,"ez"));
//entrySet():返回此映射所包含的映射关系的 Set 视图。
//Set<Map.Entry<Integer,String>> me =hm.entrySet(); Set<Map.Entry<K,V>>
/*for (Iterator<Map.Entry<Integer,List<Province>>> it =hm.entrySet().iterator();it.hasNext() ; )
{
Map.Entry<Integer,List<Province>> me =it.next();
Integer key=me.getKey();
List<Province> value =me.getValue();
sop(getCountryInfo(value));
}
//keySet();返回此映射中所包含的键的 Set 视图。 Set<K>
/*for (Iterator<Integer> it =hm.keySet().iterator(); it.hasNext(); )
{
Integer key =it.next();
String value =hm.get(key);
sop(key+"::::"+value);
}
*/
for (Iterator<Integer> it =hm.keySet().iterator(); it.hasNext(); )
{
Integer key =it.next();
List<Province> value=hm.get(key);
sop(getCountryInfo(value));
}
}
public static String getCountryInfo(List<Province> value)
{
StringBuffer sb =new StringBuffer();
Iterator<Province> it =value.iterator();
for (;it.hasNext() ; )
{
Province p =it.next();
sb.append(p.getInfo()+"\t");
}
return sb.toString();
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
复制代码
作者:
许庭洲
时间:
2014-4-24 20:56
值得学习ing!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2