赞
踩
import java.util.*; public class IteratorTest { public static void main(String[] args) { iteratorList(); iteratorSet(); iteratorMap(); } /** * 通过迭代器Iterator遍历list */ 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); } } /** * 通过迭代器Iterator遍历Set */ 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); } } /** * 通过迭代器Iterator遍历Map */ 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); } } }
import java.util.List; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public class TestThroughCollection { /** * 遍历list * @param list * @param <E> */ public static <E> void throughList(List<E> list){ //1.普通for循环 for(int i =0; i < list.size(); i++){ E e = list.get(i); System.out.println(e); } //2.增强for循环 for(E e : list){ System.out.println(e); } //3.使用Iterator迭代器(1) for(Iterator iterator = list.iterator(); iterator.hasNext();){ E e = (E)iterator.next(); System.out.println(e); } //4.使用Iterator迭代器(2) Iterator it = list.iterator(); while(it.hasNext()){ E e = (E)it.next(); System.out.println(e); } } /** * 遍历Set * @param set * @param <E> */ public static <E> void throughSet(Set<E> set){ //1.增强for循环 for(E e : set){ System.out.println(e); } //2.Iterator迭代器 for(Iterator iterator = set.iterator(); iterator.hasNext();){ E e = (E)iterator.next(); System.out.println(e); } } /** * 遍历Map * @param map * @param <K> * @param <V> */ public static <K, V> void throughMap(Map<K, V> map){ //1.根据Key获取value Set<K> set = map.keySet(); for(Iterator it = set.iterator(); it.hasNext();){ K key = (K)it.next(); V value = map.get(key); } //2.使用entrySet Set<Entry<K,V>> ss = map.entrySet(); //2.1 for(Entry<K,V> entry : ss){ System.out.println(entry); } //2.2 /* for(Iterator it = ss.iterator(); it.hasNext();){ Entry<K, V> entry = (Entry<K, V>) it.next(); System.out.println(entry); System.out.println(entry.getKey() + "=" + entry.getValue()); } */ } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。