使用Iterator迭代器遍历
1. 使用Iterator迭代器遍历List、Set、Map
import java.util.*;
public class IteratorTest {
public static void main(String[] args) {
iteratorList();
iteratorSet();
iteratorMap();
}
public static void iteratorList(){
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
for(Iterator iterator = list.iterator();iterator.hasNext(); ){
String s = (String) iterator.next();
System.out.println(s);
}
}
public static void iteratorSet(){
Set<String> set = new HashSet<>();
set.add("aa");
set.add("bb");
set.add("cc");
set.add("dd");
set.add("ee");
for(Iterator iterator = set.iterator();iterator.hasNext(); ){
String s = (String) iterator.next();
System.out.println(s);
}
}
public static void iteratorMap(){
Map<Integer, String> map = new HashMap<>();
map.put(1001,"Ano");
map.put(1002,"Jack");
map.put(1003,"Charlie");
Set<Integer> keys = map.keySet();
for(Iterator iterator = keys.iterator();iterator.hasNext();){
Integer integer = (Integer) iterator.next();
String value = map.get(integer);
System.out.println(integer +" =" +value);
}
}
}
2. 遍历容器方法汇总
import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class TestThroughCollection {
public static <E> void throughList(List<E> list){
for(int i =0; i < list.size(); i++){
E e = list.get(i);
System.out.println(e);
}
for(E e : list){
System.out.println(e);
}
for(Iterator iterator = list.iterator(); iterator.hasNext();){
E e = (E)iterator.next();
System.out.println(e);
}
Iterator it = list.iterator();
while(it.hasNext()){
E e = (E)it.next();
System.out.println(e);
}
}
public static <E> void throughSet(Set<E> set){
for(E e : set){
System.out.println(e);
}
for(Iterator iterator = set.iterator(); iterator.hasNext();){
E e = (E)iterator.next();
System.out.println(e);
}
}
public static <K, V> void throughMap(Map<K, V> map){
Set<K> set = map.keySet();
for(Iterator it = set.iterator(); it.hasNext();){
K key = (K)it.next();
V value = map.get(key);
}
Set<Entry<K,V>> ss = map.entrySet();
for(Entry<K,V> entry : ss){
System.out.println(entry);
}
}
}