Java中Map的遍历

好长时间没写用map了,今天写,突然发现不会用了。于是有了下面的练习

public class TestMap {
	public static void main(String args[]){
		Map<String,Integer> myMap = new HashMap<String,Integer>();
		
		myMap.put("a", 1);
		myMap.put("b", 12);
		myMap.put("c", 123);
		myMap.put("d", 1234);
		myMap.put("e", 12345);
		myMap.put("f", 123456);
		
		
		//使用entrySet进行遍历
		Iterator<Map.Entry<String, Integer>> it1 = myMap.entrySet().iterator();
		while(it1.hasNext()){
			Map.Entry<String, Integer> entrySet = it1.next();
			System.out.println("Key = " + entrySet.getKey() + "; Value = " + entrySet.getValue());
		}
		
		
		//使用keySet进行遍历
		Iterator<String> it2 = myMap.keySet().iterator();
		while(it2.hasNext()){
			String key = it2.next();
			System.out.println("Key = " + key + "; Value = " + myMap.get(key));
		}
		
		
		//使用collections工具类进行便利:此处得到的是value的遍历
		Collection<Integer> c1 = myMap.values();
		Iterator<Integer> it3 = c1.iterator();
		while(it3.hasNext()){
			System.out.println(it3.next());
		}
		//使用collections工具类进行便利:此处得到的是key的遍历
		Collection<String> c2 = myMap.keySet();
		Iterator<String> it4 = c2.iterator();
		while(it4.hasNext()){
			System.out.println(it4.next());
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值