Map的遍历

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


/**
 * Description:Map遍历的map.keyset和map.entryset
 * @author 李XX2019年9月19日 
 */
public class Map遍历
{
    public static void main(String[] args)
    {
        Map map = new HashMap();
        map.put("1", "value1");
        map.put("2", "value2");
        map.put("3", "value3");
        map.put("4", "value4");
        map.put("5", "value5");
        
        System.out.println("通过map.keySet遍历key和value:");
        for(String key:map.keySet())
        {
            System.out.println("Key:"+key+" Value:"+map.get(key));
        }
        
        System.out.println("\n通过map.entrySet遍历key和value:");
        for(Map.Entry entry:map.entrySet())
        {
            System.out.println("Key:"+entry.getKey()+" Value:"+entry.getValue());
        }
        
        System.out.println("\n通过map.entrySet使用Iteration遍历key和value");
        Iterator> it= map.entrySet().iterator();
        while(it.hasNext())
        {
            Map.Entry entry=it.next();
            System.out.println("Key:"+entry.getKey()+" Value:"+entry.getValue());
        }
        
        System.out.println("\n通过map.keySet使用Iteration遍历key和value");
        Iterator ite = map.keySet().iterator();
        while(ite.hasNext())
        {
            String key = ite.next();
            System.out.println("Key:"+key+" Value:"+map.get(key));
        }
        
        System.out.println("\n通过增强型for循环只遍历键或值");
        for(String s1:map.keySet())
        {
            System.out.println("Key:"+s1);
        }
        for(String s2:map.values())
        {
            System.out.println("Value:"+s2);
        }
    }
}

 

你可能感兴趣的:(Map的遍历)