集合中,使用迭代器遍历的方法

目录

 

1.使用迭代器遍历List集合

2.使用迭代器遍历Set集合

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

3.1使用map中的keySet( )方法进行获取

3.2使用map中的entrySet进行遍历


1.使用迭代器遍历List集合

package com.jredu.oopch07;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class Ch05 {
	public static void main(String[] args) {
	
		List list = new ArrayList<>();
		//集合
		list.add(1);
		list.add(2);
		list.add(3);
		
		//Iterator迭代器
		//1、获取迭代器
		Iterator iter = list.iterator();
		//2、通过循环迭代
		//hasNext():判断是否存在下一个元素
		while(iter.hasNext()){
			//如果存在,则调用next实现迭代
			//Object-->Integer-->int
			int j=(int)iter.next();  //把Object型强转成int型
			System.out.println(j);
		}
	}
}

2.使用迭代器遍历Set集合

package com.jredu.oopch08;
 
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
 
public class Ch01 {
 
	public static void main(String[] args) {
		//存储数据的地址
		Set set = new HashSet<>();
		//存储数据
		set.add(new Theme(1,"标题1","简介1"));
		set.add(new Theme(2,"标题2","简介1"));
		
		//遍历数据
		Iterator iter = set.iterator();
		while(iter.hasNext()){
			Theme theme = (Theme)iter.next();
			System.out.println(theme.getId()+theme.getTitle()+theme.getRemark());
		}
	}
}

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

3.1使用map中的keySet( )方法进行获取

public class Ch04 {
	
	public static void main(String[] args) {
		Map map=new HashMap<>();
		map.put(1, "a");
		map.put(2, "b");
		map.put(3, "c");

		//必须掌握
		//所有键值对中的键,组成成一个set集合
		Set set=map.keySet();
		//迭代键的集合
        Iterator it = set.Iterator();
        while(it.hashNext()){
            Object key = it.next();
            //获得每个键所对应的值
            object value = map.get(key);
		    system.out.println(key+"="+value);
   }
}

3.2使用map中的entrySet进行遍历

public class Ch04 {
	
	public static void main(String[] args) {
		Map map=new HashMap<>();
		map.put(1, "a");
		map.put(2, "b");
		map.put(3, "c");

		
		Set set=map.entrySet();
        Iterator it = set.Iterator();
        while(it.hashNext()){
           Map.entry entry = (Map.entry)it.next();
           object key= entry.getKey();
           object value = entyr.getValue();
		   system.out.println(key+"="+value);
   }
}

猜你喜欢

转载自blog.csdn.net/MyBloggerlxs/article/details/81638393