遍歷map的幾種方式
阿新 • • 發佈:2021-02-18
技術標籤:java
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < 100000; i++) {
map.put(“資料” + i, i);
}
①只獲取key值或者value值
1.獲取key:keySet()
Set set = map.keySet();
for (String s : set) {
System.out.println(s);
}
2.獲取value:values()
Collection values = map.values();
for (Integer value : values) {
}
②同時獲取key和value
1.使用keySet()先獲取key,再使用get(key)獲取value (效能低,不推薦)
Set set1 = map.keySet();
for (String s : set1) {
System.out.println(s + “–” + map.get(s));
}
2.使用entrySet() (效能高,推薦使用)
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
}
③使用Iterator遍歷
優點:在用foreach遍歷map時,如果改變其大小,會報錯,但如果只是刪除元素,可以使用Iterator的remove方法刪除元素
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> next = iterator.next();
}
④使用Lambda遍歷
java8開始提供,書寫簡潔,效能低於entrySet()
map.forEach((key, value) -> {
System.out.println(key + “–” + value);
})
幾種方法測試時間:
測試程式碼:
public void test1() {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < 100000; i++) {
map.put("資料" + i, i);
}
long begin1 = System.currentTimeMillis();
Set<String> set = map.keySet();
for (String s : set) {
System.out.println(s);
}
long end1 = System.currentTimeMillis();
long begin2 = System.currentTimeMillis();
Collection<Integer> values = map.values();
for (Integer value : values) {
System.out.println(value);
}
long end2 = System.currentTimeMillis();
long begin3 = System.currentTimeMillis();
Set<String> set1 = map.keySet();
for (String s : set1) {
System.out.println(s + "--" + map.get(s));
}
long end3 = System.currentTimeMillis();
long begin4 = System.currentTimeMillis();
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
System.out.println(entry.getKey() + "--" + entry.getValue());
}
long end4 = System.currentTimeMillis();
long begin5 = System.currentTimeMillis();
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> next = iterator.next();
System.out.println(next.getKey() + "--" + next.getValue());
}
long end5 = System.currentTimeMillis();
long begin6 = System.currentTimeMillis();
map.forEach((key, value) -> {
System.out.println(key + "--" + value);
});
long end6 = System.currentTimeMillis();
System.out.println("keySet:" + (end1 - begin1));
System.out.println("values:" + (end2 - begin2));
System.out.println("keySet+get(key):" + (end3 - begin3));
System.out.println("entrySet:" + (end4 - begin4));
System.out.println("entrySet.iterator:" + (end5 - begin5));
System.out.println("Lambda:" + (end6 - begin6));
}