Map集合三种遍历方式

Map集合三种遍历方式

1.迭代器遍历

package lession02;

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

public class Demo2 {
	public static void main(String[] args) {
		Map<String,String> map = new HashMap<>();
		
		map.put("杨过", "男");
		map.put("小龙女", "女");
		map.put("蛮子", "男");
		map.put("艾希","女");
		
		System.out.println(map);
		// 遍历map集合
		// 1.迭代器遍历
		Set<String> keySets = map.keySet();	
		Iterator<String> ki = keySets.iterator();
		
		while(ki.hasNext()){
			String k = ki.next();
			String v = map.get(k);
			
			System.out.println(k+"-->"+v);
		}
	
	}
}

运行结果

运行结果1

2.增强for遍历(内部原理:迭代器遍历)

package lession02;

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

public class Demo3 {
	public static void main(String[] args) {
		Map<String,String> map = new HashMap<>();
		
		map.put("杨过", "男");
		map.put("小龙女", "女");
		map.put("蛮子", "男");
		map.put("艾希","女");
		
		System.out.println(map);
		Set<String> keySets = map.keySet();	
		// 2.增强for循环遍历
		for(String key:keySets){
			String value = map.get(key);
			System.out.println(key+"---->"+value);
		}
		
	}
}

运行结果

运行结果2

3.entrySet遍历

package lession02;

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

public class Demo4 {
	public static void main(String[] args) {
		Map<String,String> map = new HashMap<>();
		
		map.put("杨过", "男");
		map.put("小龙女", "女");
		map.put("蛮子", "男");
		map.put("艾希","女");	
		
		System.out.println(map);
		// 3.entrySet遍历
		Set<Entry<String, String>> entry =  map.entrySet();
		for(Entry<String, String> en:entry){
			System.out.println(en.getKey()+"--->"+en.getValue());
		}
	}
}

运行结果

运行结果2

Entry方式遍历过程模拟

Map-entry遍历

posted @ 2019-07-18 22:07  大彪哥55  阅读(4807)  评论(0编辑  收藏  举报