Map的三种遍历方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DongGeDeBoKe/article/details/76172093
package com.qf.day13;

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

public class work9 {
    public static void main(String[] args) {
        Map<String, Object> map=new HashMap<>();
        for(int i=0;i<10;i++){
            map.put(""+i, i);
        }
        System.out.println("用Map的内部类Entry,来遍历Map集合");
        Set<Entry<String, Object>> entrySet = map.entrySet();
        for(Entry<String,Object> entry:entrySet){
            System.out.println(entry.getKey()+"-"+entry.getValue());
        }
        System.out.println("利用迭代器,遍历Map集合");
        Iterator<String> iterator=map.keySet().iterator();
        while(iterator.hasNext()){
            String id=iterator.next();
            System.out.println(id+"-"+map.get(id));
        }
        System.out.println("遍历values");
        Collection<Object> collection=map.values();
        for(Object object:collection){
            System.out.println(object);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/DongGeDeBoKe/article/details/76172093