package com.tang;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
/**
* 遍历 HashMap 的 5 种最佳方式:
*
* 1.使用 Iterator 遍历 HashMap EntrySet
*
* 2.使用 Iterator 遍历HashMap KeySet
*
* 3.使用 For-each 循环迭代 HashMap
*
* 4.使用 Lambda 表达式遍历 HashMap
*
* 5.使用 Stream API 遍历 HashMap
*
*
*/
public class TestMap {
// 1.使用 Iterator 遍历 HashMap EntrySet
@Test
public void test1() {
Map<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "JAVA");
hashMap.put(2, "Python");
hashMap.put(3, "C");
hashMap.put(4, "C++");
hashMap.put(5, "C#");
hashMap.put(6, "Scala");
Iterator<Entry<Integer, String>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Integer, String> next = iterator.next();
System.out.println(next.getKe
遍历 HashMap 的 5 种最佳方式:
最新推荐文章于 2024-06-27 15:25:28 发布
![](https://img-home.csdnimg.cn/images/20240611030827.png)