HashMap的三种获取全部key的方式

import java.util.HashMap;
import java.util.Iterator;
public class TestMap {

    //how to get key set?
    public static void main(String[] args) {
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(1,1);
        map.put(2,1);
        map.put(3,1);
        map.put(4,1);

		//first way
		for(int key : map.keySet()){
			System.out.println(key);
		}
        //second way (推荐)
        for(HashMap.Entry<Integer,Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey());
        }
        //third way
        Iterator<HashMap.Entry<Integer,Integer>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next().getKey());
        }
    }
}

你可能感兴趣的:(java相关)