Java HashMap 学习笔记
1. 一个简单例子介绍关于Java HashMap 的基本操作:创建、添加、更新、删除及遍历。
2. 代码:
1 import java.util.*; 2 3 /** 4 * the basic usage of hashmap 5 * @author SheepCore 6 * @date 2020-03-03 7 */ 8 public class Main { 9 public static void main(String[] args) { 10 //Created a hashmap and named it fruitStore 11 Map<String, Float> fruitStore = new HashMap<>(); 12 13 //add some fruit with the tag <name, price> into fruitStore 14 fruitStore.put("Apple", 8.98f); 15 fruitStore.put("Dragon Fruit", 5.98f); 16 fruitStore.put("Red Grape", 6.98f); 17 fruitStore.put("Banana", 4.98f); 18 fruitStore.put("Durian", 32.8f); 19 20 //update the price of Apple 21 fruitStore.put("Apple", 7.50f); 22 23 //the store sold out all the banana, so remove it from the store 24 fruitStore.remove("Banana"); 25 fruitStore.put("Orange", 4.85f); 26 27 //show all kinds of fruit in the store 28 Iterator iter = fruitStore.entrySet().iterator(); 29 while (iter.hasNext()) { 30 Map.Entry entry = (Map.Entry)iter.next(); 31 String name = (String)entry.getKey(); 32 float price = (float)entry.getValue(); 33 System.out.printf("%-15s %-5.2f\n", name, price); 34 } 35 36 //count the average price of all fruit in the store 37 Iterator iter2 = fruitStore.values().iterator(); 38 float sum = 0f; 39 while (iter2.hasNext()) { 40 sum += (float)iter2.next(); 41 } 42 System.out.printf("Average Price: ¥%.2f\n", sum / fruitStore.size()); 43 } 44 }