hashMap的遍历

今天写的一个算法中用到了hashMap,于是将其学习一下

普通HashMap的遍历

 1 HashMap<String,String> student=new HashMap<String,String>();
 2         student.put("a", "grade 1");
 3         student.put("b", "grade 2");
 4         student.put("c", "grade 3");
 5         Iterator it=student.keySet().iterator();
 6         while(it.hasNext())
 7         {
 8             String m=(String)it.next();
 9             System.out.println("key="+m+" value="+student.get(m));
10         }
11         //第二种
12         Set<Entry<String, String>> sets = student.entrySet();  
13         for(Entry<String, String> entry : sets) {  
14             System.out.print(entry.getKey() + ", ");  
15             System.out.println(entry.getValue());  
16         }  
17         //第三种
18         HashMap<String,Integer> studentScore=new HashMap<String,Integer>();
19         studentScore.put("a", 98);
20         studentScore.put("b", 78);
21         studentScore.put("c", 89);
22         Iterator iit=studentScore.keySet().iterator();
23         while(iit.hasNext())
24         {
25             String m=(String)iit.next();
26             System.out.println("key="+m+" value="+studentScore.get(m));
27         }
View Code

含有HashMap的value是ArrayList时

 1 Iterator<Entry<String, ArrayList<TreeNode>>> it = linkedNode.entrySet().iterator();
 2                 while( it.hasNext())
 3                 {
 4                     Map.Entry<String, ArrayList<TreeNode>> entry = it.next();
 5                     String key = entry.getKey();
 6                     ArrayList<TreeNode> values=(ArrayList<TreeNode>)entry.getValue();
 7                     for(TreeNode value:values)
 8                     {
 9                         System.out.print(" name="+value.getName()+" count="+value.getCount());
10                     }
11                     System.out.println();
12                     //TreeNode tempNode= entry.getValue().get(i);
13                 }
14                 
View Code
原文地址:https://www.cnblogs.com/huicpc0212/p/4346233.html