標籤:nta == put map entry hash java key item
摘要:作為HashMap系列學習筆記的開篇,我認為要先熟悉HashMap的使用情境。
==========================================================================================
Map本質上還是屬於集合類型的資料結構。
下面的程式碼片段示範了Map的常用操作(CURD),注意遍曆Map盡量使用Entry方式。
1 HashMap<String, Double> scores = new HashMap<>(); 2 3 scores.put("Sam", 100.0); 4 scores.put("Jacky", 50.0); 5 scores.put("Tim", 80.0); 6 7 System.out.print(scores); 8 9 scores.put("Tim", 100.0);10 System.out.print(scores);11 System.out.print(scores.toString());12 13 System.out.print(scores.get("Sam"));14 15 System.out.println(scores.containsKey("Sam"));16 System.out.println(scores.containsValue(100.0));17 18 //traverse, cost more time19 Iterator<String> it = scores.keySet().iterator();20 while(it.hasNext()) {21 String tmp = it.next();22 System.out.println(tmp);23 System.out.println(scores.get(tmp));24 }25 26 System.out.println("count of student:" + scores.size());27 System.out.println("scores is " + (scores.isEmpty() ? "empty" : "not empty"));28 29 //traverse and delete target, cost less30 Iterator<Map.Entry<String, Double>> begIt = scores.entrySet().iterator();31 for(; begIt.hasNext(); ) {32 Map.Entry<String, Double> item = begIt.next();33 34 if(item.getValue() == 100.0) {35 begIt.remove();36 }37 }38 39 System.out.println(scores);40 41 scores.clear();42 System.out.println(scores);
輸出如下:
{Tim=80.0, Jacky=50.0, Sam=100.0}{Tim=100.0, Jacky=50.0, Sam=100.0}{Tim=100.0, Jacky=50.0, Sam=100.0}100.0true
true
Tim
100.0
Jacky
50.0
Sam
100.0
count of student:3
scores is not empty
{Jacky=50.0}
{}
PS:實際項目中HashMap用的不多,複雜的操作(如key為HashMap)就不做示範了。
【JAVA】HashMap入門到放棄:使用HashMap