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

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

	@Test
	public void test1() throws Exception {
		Map<Integer, String> map = new HashMap<>();
		map.put(1, "a");
		map.put(3, "c");
		map.put(5, "e");
		map.put(2, "b");
		for (Map.Entry<Integer, String> 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<Integer, String> 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<Integer, String> map = new HashMap<>();
		map.put(1, "a");
		map.put(3, "c");
		map.put(5, "e");
		map.put(2, "b");
		Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>)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<Integer, String> 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

    原文作者:lavachen
    原文地址: https://blog.csdn.net/ChasingDreamsCQ/article/details/89467060
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞