Java集合的迭代(遍历)

1.Java的接口Iterator(迭代器)描述了逐一便利的方法。

2.Iterator描述了一个顺序结构,且有一个游标概念。游标默认在第一个元素之前,调用方法hasNext()可以检查游标是否含有下一个元素。使用Next()方法移动游标,且返回当前游标所指向的元素。这两个方法经常与while循环组成模块化结构,用来遍历集合内容,是常见的标准化结构。

3.凡是对集合的遍历都采用Iterator接口实现,编程中十分常见。

4.集合在迭代期间不能调用集合的更新方法:add、remove、set等

5.如需迭代期间删除集合内容,应调用迭代器的删除方法remove删除当前元素。

hashSet的迭代:

package HashSetDemo;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetDemo {
	public static void main(String[] args) {
		Set<String> str= new HashSet<String>();
		str.add("A");
		str.add("B");
		str.add("C");
		str.add("A");
		str.add("A");
		str.add("D");
		str.add("A");

		str.add("A");
		System.out.println(str.size());//4,Set不包含重复元素
		for(@SuppressWarnings("rawtypes")
		Iterator ite=str.iterator();ite.hasNext();){
			System.out.println((String)ite.next());//hash算法
		}
	}
}

hashMap的迭代

package MapDemo;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapDemo {

	/**
	 * 统计一字符串中每个字符的数量
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) {
		String str="assfksjdjhdjasaaa";
		System.out.println(Count(str));
		//Map的迭代
		Set<Map.Entry> set=(Set)Count(str).entrySet();//entrySet:条目集合;Map.Entry(Map条):静态接口;可看做Map转Set;
		Iterator ite=set.iterator();
		while(ite.hasNext()){
			Map.Entry entry=(Map.Entry)ite.next();
			System.out.println("字母"+entry.getKey()+"的数量为"+entry.getValue());
		}
		//Map的迭代2
		Set<Character> set1=Count(str).keySet();
		Iterator iter=set1.iterator();
		while(iter.hasNext()){
			char c=(Character)iter.next();
			int value=Count(str).get(c);
			System.out.println("字母"+c+"的数量为"+value);
		}
	}
	public static Map<Character,Integer>Count(String str){// Map<Character,Integer>:Character为char的包装类;Integer为int的包装类
		Map<Character,Integer> map=new HashMap<Character,Integer>();
		for(int i=0;i<str.length();i++){
			char c=str.charAt(i);
			if(map.containsKey(c)){//自动包装
				map.put(c, map.get(c)+1);//自动包装
			}else{
				map.put(c, 1);//自动包装
			}
		}
		return map;
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值