首页 > 技术文章 > think in java读后总结---Map集合的几种遍历方式

dahao1020 2016-03-06 15:35 原文

代码很简单哈,算是对基础知识的一个总结和回顾吧,先上代码:

/**
 * Map集合的几种遍历方式
 * @author wxh
 * @vertion 1.0
 */
public class DemoMap {
    
    private static Map<Integer,String> getMap() {
        Map<Integer,String> map = new HashMap<Integer,String>();
        map.put( 1, "wxh1" );
        map.put( 2, "wxh2" );
        map.put( 3, "wxh3" );
        map.put( 4, "wxh4" );
        return map;
    }
    
    /**
     * 直接遍历
     */
    @Test
    public void test01() {
        Set<Entry<Integer, String>> set = getMap().entrySet();
        Iterator<Entry<Integer, String>> it = set.iterator();
        while( it.hasNext() ) {
            Entry<Integer, String> e = it.next();
            System.out.println( e.getKey() + "==" + e.getValue() );
        }
    }
    
    /**
     * 用增强for循环遍历
     */
    @Test
    public void test02() {
        for( Entry<Integer, String> e : getMap().entrySet() ) {
            System.out.println( e.getKey() + "==" + e.getValue() );
        }
    }
    
    /**
     * 根据key获取value
     */
    @Test
    public void test03() {
        Set<Integer> set = getMap().keySet();
        Iterator<Integer> it = set.iterator();
        while( it.hasNext() ) {
            Integer key = it.next();
            String value = getMap().get( key );
            System.out.println( key + "==" + value );
        }
    }
    
    /**
     * 通过增强for循环根据key获取value
     */
    @Test
    public void test04() {
        for( Integer key : getMap().keySet() ) {
            String value = getMap().get( key );
            System.out.println( key + "==" + value );
        }
    }
}

 

推荐阅读