package cn.sxt.mycollection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class TestIterator {
public static void main(String[] args){
TestIteratorList();
TestIteratorSet();
TestIteratorMap();
}
public static void TestIteratorList(){
List<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
//for遍历ArrayList
for(String i:list){
System.out.println("1--"+i);
}
for(int i=0;i<list.size();i++){
System.out.println("2--"+list.get(i));
}
//使用iterator迭代器遍历list
for(Iterator<String> iter = list.iterator();iter.hasNext();){
String temp = iter.next();
System.out.println(temp);
}
// 获取迭代器
Iterator<String> it = list.iterator();
// 输出集合中的所有元素
while(it.hasNext()) {
System.out.println("while"+"--"+it.next());
}
}
public static void TestIteratorSet(){
Set<String> set = new HashSet<>();//Set/HashSet
set.add("aa");
set.add("bb");
set.add("cc");
for(String i:set){
System.out.println("1--"+i);
}
//使用iterator迭代器遍历list
for(Iterator<String> iter = set.iterator();iter.hasNext();){
String temp = iter.next();
System.out.println(temp);
}
// 获取迭代器
Iterator<String> it = set.iterator();
// 输出集合中的所有元素
while(it.hasNext()) {
System.out.println("while"+"--"+it.next());
}
}
public static void TestIteratorMap(){
Map<Integer,String> map1 = new HashMap<Integer,String>();//Map/HashMap都可以
map1.put(100,"aa");
map1.put(200,"bb");
map1.put(300,"cc");
//iterator第一种遍历map的方式(键值对)
System.out.println("iterator第一种遍历map的方式");
Set<Entry<Integer,String>> ss = map1.entrySet();//Map.Entry/Entry都可以
for(Iterator<Entry<Integer,String>> iter = ss.iterator();iter.hasNext();){
Entry<Integer,String> temp =iter.next();//包含键和值
System.out.println(temp.getKey()+"--"+temp.getValue());
}
Iterator<Entry<Integer,String>> it = ss.iterator();
while (it.hasNext()) {
Map.Entry<Integer,String> s = it.next();
System.out.println("while--"+s.getKey()+"-"+s.getValue());
}
//iterator第二种遍历map的方式(键)
System.out.println("iterator第二种遍历map的方式");
Set<Integer> keySet = map1.keySet();//获取map所有键的集合
for(Iterator<Integer> iter1 =keySet.iterator();iter1.hasNext();){
Integer key = iter1.next();
System.out.println(key+"--"+map1.get(key));
}
Iterator<Integer> iter =keySet.iterator();
while (iter.hasNext()) {
Integer key = iter.next();
String value = map1.get(key);
System.out.println("while--"+key+"-"+value);
}
}
}
网友评论