Java Map的几种循环方式学习总结

1:根据JDK的新特性,用For循环Map,例如循环Map的Key

Map map = new HashMap();
		for (int i = 0; i < 10; i++) {
			map.put(i, i+1);
		}
		for (Object key : map.keySet()) {
			System.out.println("key = " + key);
		} 
  

 2:对整Map的key和value都进行循环,如下: 
  

for(Map.Entry entry : paraMap.entrySet())    
{    
    System.out.println(entry.getKey()+": "+entry.getValue());    
} 

3:使用Iterator 

Iterator it = paraMap.entrySet().iterator();    
while (it.hasNext())     
{    
        Map.Entry map = (Map.Entry)it.next();    
        System.out.println(map .getKey() + " = " + map .getValue());    
 }  


对上面的内容进行更新!将三种方式完整呈现!

package com.dufyun.javase.jihe;

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

/**
 * 练习循环map集合中key和value的方法
 * @author aflyun
 * 
 *
 */
public class TestMap {
	
	   
	public static void main(String[] args) {
		Map map = new HashMap();
		for (int i = 0; i < 10; i++) {
			map.put(i, i+1);
		}
		
		firstLoopMap(map);
		secodnLoopMap(map);
		thirdLoopMap(map);
	}
	
	/**
	 * 1:循环 map 中的key
* 根据JDK的新特性,用For循环Map,例如循环Map的Key 和 value * @param map */ public static void firstLoopMap(Map map) { for (Object key : map.keySet()) { System.out.println("key = " + key +"--value = " + map.get(key)); } } /** * 2:循环 map 中的key 和 value
* entrySet * @param map */ public static void secodnLoopMap(Map map) { for (Map.Entry entry : map.entrySet()) { System.out.println("key = " + entry.getKey() +"--value = " + entry.getValue()); } } /** * 3:循环Map的key 和value
* iterator * @param map */ public static void thirdLoopMap(Map map) { Iterator it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry m = (Entry) it.next(); System.out.println("key = " + m.getKey() +"---value = "+ m.getValue()); } } }
输出的内容:

key = 0---value = 1
key = 1---value = 2
key = 2---value = 3
key = 3---value = 4
key = 4---value = 5
key = 5---value = 6
key = 6---value = 7
key = 7---value = 8
key = 8---value = 9
key = 9---value = 10



你可能感兴趣的:(Java基础)