HashMap遍历的几种方法

HashMap遍历的几种方法

写一下HashMap遍历的几种方法,以后自己使用方便

public static void main(String[] args) {
		HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
		hashMap.put("a", 1);
		hashMap.put("b", 2);
		hashMap.put("c", 2);

		Integer getValue = hashMap.get("a");
		System.out.println(getValue);
		
		//迭代器遍历
		System.out.println("======keySet遍历======");

		Iterator<String> iteratorMap1 = hashMap.keySet().iterator();
		while (iteratorMap1.hasNext()) {
			String key = iteratorMap1.next();
			Integer value = hashMap.get(key);
			System.out.println(key+"="+value);
		}
		
		
		System.out.println("======entrySet遍历======");

		Iterator<Entry<String, Integer>> iteratorMap2 = hashMap.entrySet().iterator();
		while (iteratorMap2.hasNext()) {
			Entry<String, Integer> nextMap = iteratorMap2.next();
			String key = nextMap.getKey();
			Integer value = nextMap.getValue();
			System.out.println(key+"="+value);
		}
		
		//增强for循环
		System.out.println("======增强for循环keySet遍历======");
		
		for(String key : hashMap.keySet()) {
			System.out.println(key+"="+hashMap.get(key));
		}
		
		System.out.println("======增强for循环entrySet遍历======"); 
		for(Entry<String, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey()+"="+entry.getValue());
		}
	}
发布了15 篇原创文章 · 获赞 20 · 访问量 1919

猜你喜欢

转载自blog.csdn.net/OliverND/article/details/103435807