1. HashMap遍历
/*HashMap的遍历
EntrySet遍历方法,可以得到一个Entry对象的结果集,然后使用Entry对象的getKey和getValue方法。
KeySet遍历方法,先使用keySet函数,获取到HashMap的所有Key的集合对象,然后循环所有的key,
通过HashMap的get方法,获取到对应的value。*/
packagecom.zyy.collectionPrint;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
public classHashMapPrint {
public static void main(String[] args) {
HashMap<String,String>hm=new HashMap<String,String>();
hm.put("1","a");
hm.put("2","b");
hm.put("3","c");
//最简洁、最通用的遍历方式
for(Map.Entry<String,String> entry:hm.entrySet()){
System.out.println(entry.getKey()+"="+entry.getValue());
}
//java5只之前的比较简洁的遍历方式
for(Iterator<Map.Entry<String,String>>it=hm.entrySet().iterator();it.hasNext();){
Map.Entry<String,String> entry=it.next();
System.out.println(entry.getKey()+"="+entry.getValue());
}
//java5之前的比较简洁的遍历方式2
for(Iterator<String>it=hm.keySet().iterator();it.hasNext();){
String key=it.next();
System.out.println(key+"="+hm.get(key));
}
}
}
2. Queue的遍历
下表显示了jdk1.5中的阻塞队列的操作:
add
remove
element
offer
poll
peek
put
take
//队列的遍历
packagecom.zyy.collectionPrint;
importjava.util.Queue;
importjava.util.concurrent.LinkedBlockingQueue;
public classQueuePrint {
public static void main(String[] args) {
Queue<Integer> q=newLinkedBlockingQueue<Integer>();
//初始化队列
for(int i=0;i<5;i++){
q.offer(i);
}
//集合方式遍历,元素不会被移除
for(Integer x:q){
System.out.print(x+"");
}
//队列方式遍历,元素逐个被移除
while(q.peek()!=null){
System.out.print(q.poll()+"");
}
}
}
3. Stack的遍历
//stack的遍历
packagecom.zyy.collectionPrint;
importjava.util.Stack;
public classStackPrint {
public static void main(String[] args) {
Stack<Integer> s=newStack<Integer>();
for(int i=0;i<10;i++){
s.push(i);
}
//集合遍历方式
for(Integer x:s){
System.out.print(x+"");
}
System.out.println();
//栈弹出遍历
while(!s.empty()){
System.out.print(s.pop()+"");
}
}
}
4. List遍历
//遍历ArrayList
packagecom.zyy.collectionPrint;
importjava.util.ArrayList;
public classListPrint {
public static void main(String[] args) {
ArrayList<String> al=newArrayList<String>();
al.add("a");
al.add("b");
al.add("c");
//集合遍历
for(String s:al){
System.out.print(s+"");
}
}
}