Java:使用Iterator迭代器遍历集合数据

时间:2025-04-24 06:55:56

1、使用迭代器遍历ArrayList集合

package .oopch07;

import ;
import ;
import ;

public class Ch05 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		List list = new ArrayList<>();
		
		//集合
		(1);
		(2);
		(3);
		
		//Iterator迭代器
		//1、获取迭代器
		Iterator iter = ();
		//2、通过循环迭代
		//hasNext():判断是否存在下一个元素
		while(()){
			//如果存在,则调用next实现迭代
			//Object-->Integer-->int
			int j=(int)();  //把Object型强转成int型
			(j);
		}
	}

}
2、使用迭代器遍历Set集合

package .oopch08;

import ;
import ;
import ;

public class Ch01 {

	public static void main(String[] args) {
		//存储数据的地址
		Set set = new HashSet<>();
		//存储数据
		(new Theme(1,"标题1","简介1"));
		(new Theme(2,"标题2","简介1"));
		
		//遍历数据
		Iterator iter = ();
		while(()){
			Theme theme = (Theme)();
			(()+()+());
		}
	}
}

3、使用迭代器遍历Map集合

package .oopch08;

import ;
import ;
import ;
import ;
import ;

public class Ch03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map map = new HashMap<>();
		(1, "a");
		(2, "b");
		(3, "c");
		//所有键值对中的键,组成一个集合
		Set set = ();
		Iterator iter = ();
		while(()){
			(());//打印出map中的键(1,2,3)
		}
		
		
		//打印出值
		//values所有的值组成的一个集合
		Collection col = ();
		//重写了toString方法
		(col);//打印出a,b,c的值
	}

}

package .oopch08;

import ;
import ;
import ;
import ;
import ;

public class Ch04 {
	
	public static void main(String[] args) {
		Map map=new HashMap<>();
		(1, "a");
		(2, "b");
		(3, "c");
		//必须掌握
		//所有键值对中的键,组成成一个set集合
		Set set=();
		(set);
		//values所有的值组成的一个集合
		Collection col=();
		(col);
		
		
		
		
		
		//获取所有的键和值
		//entrySet可以得到由所有键值对组成的集合
		//里边存储的是所有的数据(键-值)
		Set<<Integer, String>> entrySet=();
		Iterator<<Integer, String>> iter=();
		while(()) {
			<Integer, String> entry=();
			("键:"+());
			("值:"+());
		}
//		Iterator iter=();
//		while(()) {
//			(());
//		}
//		Iterator iter=();
//		while(()) {
//			(());
//		}
//		(map);
	}

}