Java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class DictionaryDemo {
public static void main(String[] args) {
Map<String, String> animal = new HashMap<String, String>();
System.out.println("請輸入三組單詞對應的註釋,並存放到HashMap中");
Scanner console = new Scanner(System.in);
int i = 0;
// 添加數據
while (i < 3) {
System.out.println("請輸入Key值");
String key = console.next();
System.out.println("請輸入value值(註釋)");
String value = console.next();
animal.put(key, value);
i++;
}
// 打印輸出value的值(直接使用迭代器)
System.out.println("*******************");
System.out.println("使用迭代器輸出所有的value:");
Iterator<String> it = animal.values().iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.println("*******************");
// 打印輸出key和value的值
// 通過entrySet方法
System.out.println("通過entrySet方法得到key-value:");
Set<Entry<String, String>> entrySet = animal.entrySet();
for (Entry<String, String> entry : entrySet) {
System.out.print(entry.getKey() + "-");
System.out.println(entry.getValue());
}
System.out.println();
System.out.println("*******************");
// 通過單詞找到註釋並輸出
// 使用keySet方法
System.out.println("請輸入要查找的單詞:");
String strSearch = console.next();
// 1.取得keySet
Set<String> keySet = animal.keySet();
// 2.遍歷keySet
for (String key : keySet) {
if (strSearch.equals(key)) {
System.out.println("找到了!" + "鍵值對爲:" + key + "-" + animal.get(key));
break;
}
}
}
}
Java Map集合使用方法介紹(1)——在字典中添加內容並顯示
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.