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.getKey() + " " + next.getValue());
}
}
// 2.使用 Iterator 遍歷HashMap KeySet
@Test
public void test2() {
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<Integer> iterator = hashMap.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
String string = hashMap.get(key);
System.out.println(key + " " + string);
}
}
// 3.使用 For-each 循環迭代 HashMap
@Test
public void test3() {
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");
for (Map.Entry<Integer, String> entrySet : hashMap.entrySet()) {
Integer key = entrySet.getKey();
String value = entrySet.getValue();
System.out.println(key + " " + value);
}
}
@Test
// 4.使用 Lambda 表達式遍歷 HashMap
public void test4() {
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");
hashMap.forEach((key, value) -> {
System.out.println(key + " " + value);
});
}
@Test
// 5.使用 Stream API 遍歷 HashMap
public void test5() {
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");
hashMap.entrySet().stream().forEach((entry) -> {
System.out.println(entry.getKey() + " " + entry.getValue());
});
}
}