public class Test3 {
public static void main(String[] args) throws Exception {
Map<String, Double> map = new HashMap<>();
map.put("番茄", 5.6);
map.put("海参", 25.0);
map.put("土豆", 5.6);
map.put("宽粉", 2.3);
// 第一种遍历统计
int count1 = 0;
for (String str : map.keySet()) {
System.out.println(str + "=" + map.get(str));
Double d = map.get(str);
count1++;
}
System.out.println("一共有" + count1 + "食物");
Set<Map.Entry<String, Double>> sme = map.entrySet();
int count2 = 0;
Iterator<Map.Entry<String, Double>> it = sme.iterator();
while (it.hasNext()) {
Map.Entry<String, Double> x = it.next();
String key = x.getKey();
Double value = x.getValue();
System.out.println(key + "=" + value);
count2++;
}
System.out.println("一共有" + count2 + "食物");
/*
* for(Entry<String, Integer> en : map.entrySet()) {
* System.out.println(en.getKey() + "=" + en.getValue()); }
*/
// 将海参价格修改
map.put("海参", 10.9);
// 删除番茄
map.remove("番茄");
BufferedWriter bw = new BufferedWriter(new FileWriter("info.txt"));
for (String str : map.keySet()) {
System.out.println(str + "=" + map.get(str));
bw.write(str + "=" + map.get(str));
bw.newLine();
}
bw.close();
}
} |
|