HashMap遍历的常用四种方式 ——应用JAVA8新特性Lambda表达式

前言:本文将为你展示Java中HashMap的四种典型遍历方式。
如果你使用Java8,由于该版本JDK支持lambda表达式,可以采用第4种方式来遍历。
一:通过forEach循环遍历

	@Test
	public void test1() throws Exception {
		Map map = new HashMap<>();
		map.put(1, "a");
		map.put(3, "c");
		map.put(5, "e");
		map.put(2, "b");
		for (Map.Entry entry : map.entrySet()) {
			System.out.println("Key = " + entry.getKey() + " Value = "+ entry.getValue());
		}
	}

输出结果:
Key = 1 Value = a
Key = 2 Value = b
Key = 3 Value = c
Key = 5 Value = e

二:通过forEach迭代键值对 如果你只想使用键或者值,推荐使用此方式

	@Test
	public void test2() throws Exception {
		Map map = new HashMap<>();
		map.put(1, "a");
		map.put(3, "c");
		map.put(5, "e");
		map.put(2, "b");
		for (Integer key : map.keySet()) {
			System.out.println("Key = " + key);
		}
		for (String value : map.values()) {
			System.out.println("Value = " + value);
		}
	}

输出结果:
Key = 1
Key = 2
Key = 3
Key = 5
Value = a
Value = b
Value = c
Value = e

三:使用迭代器进行遍历

	@Test
	public void test3() throws Exception {
		Map map = new HashMap<>();
		map.put(1, "a");
		map.put(3, "c");
		map.put(5, "e");
		map.put(2, "b");
		Iterator> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry entry = (Map.Entry)iterator.next();
			Integer key = entry.getKey();
			String value = entry.getValue();
			System.out.println("Key = " + key + " Value = "+ value);	
		}
	}

输出结果:
Key = 1 Value = a
Key = 2 Value = b
Key = 3 Value = c
Key = 5 Value = e

四:强烈推荐通过Java8 Lambda表达式遍历

	@Test
	public void test4() throws Exception {
		Map map = new HashMap<>();
		map.put(1, "a");
		map.put(3, "c");
		map.put(5, "e");
		map.put(2, "b");
		map.forEach((key, value) -> {
			System.out.println("Key = " + key + "  " + " Value = " + value);
		});
	}

输出结果:
Key = 1 Value = a
Key = 2 Value = b
Key = 3 Value = c
Key = 5 Value = e

你可能感兴趣的:(java问题)