HashMap的几种遍历方式

public static void main(String[] args) {

        HashMap map = new HashMap<>();

        map.put("01","卡卡罗特");

        map.put("02","贝吉塔");

        map.put("03","比鲁斯");

        map.put("04", "维斯");

        System.out.println("--------------遍历方式一--------------");

        Set keySet = map.keySet();

        for(String key : keySet){

            System.out.println("key为:"+key+",value为:"+map.get(key));

        }

        System.out.println("--------------遍历方式二--------------");

        Iterator iterator = map.keySet().iterator();

        while (iterator.hasNext()){

            String next = iterator.next();

            // 错误写法,如下注释内容

            // System.out.println("key为:"+iterator.next()+",value为:"+map.get(iterator.next()));

            System.out.println("key为:"+next+",value为:"+map.get(next));

        }

        System.out.println("--------------遍历方式三--------------");

        for(Map.Entry entry : map.entrySet()){

            System.out.println("key为:"+entry.getKey()+",value为:"+entry.getValue());

        }

        System.out.println("--------------遍历方式四--------------");

        Iterator> iterator1 = map.entrySet().iterator();

        while (iterator1.hasNext()){

            Map.Entry entry = iterator1.next();

            // 错误写法,如下注释内容

            // System.out.println("key为:"+iterator1.next()+",value为:"+map.get(iterator1.next()));

            System.out.println("key为:"+entry.getKey()+",value为:"+entry.getValue());

        }

        System.out.println("--------------遍历方式五--------------");

        for(String str : map.values()){

            System.out.println("value为:"+str);

        }

    }

 

你可能感兴趣的:(Java,hashmap,java)