在字典中添加内容并显示
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 ++;
}
输出:
请输入三组单词及对应的注释,并存放到HashMap中
请输入key值(单词):
cat
请输入value值(注释):
猫
请输入key值(单词):
dog
请输入value值(注释):
狗
请输入key值(单词):
pig
请输入value值(注释):
猪
只打印输出value的值:
//打印输出value的值(直接使用迭代器)
System.out.println("*******************************");
System.out.println("使用迭代器输出所有的value:");
Iterator it = animal.values().iterator();
while(it.hasNext()){
System.out.print(it.next() + " ");
}
输出:
*******************************
使用迭代器输出所有的value:
猫 狗 猪
使用entrySet方法打印输出key和value的值:
//打印输出key和value的值
//通过entrySet的方法
System.out.println("通过entrySet方法得到key-value:");
Set<Entry<String, String>> entrySet = animal.entrySet();
for(Entry entry:entrySet){
System.out.print(entry.getKey() + "-");
System.out.println(entry.getValue());
}
输出:
通过entrySet方法得到key-value:
cat-猫
dog-狗
pig-猪
通过单词找到注释并输出:
//通过单词找到注释并输出
//使用keySet方法
System.out.println("******************************");
System.out.println("请输入要查找的单词:");
String strSearch = console.next();
Set<String> keySet = animal.keySet();
boolean flag = false;
for(String key:keySet){
if(key.equals(strSearch)){
flag = true;
break;
}
}
if(flag){
System.out.println("找到了 " + "键值对为:" + strSearch + "-" + animal.get(strSearch));
}else{
System.out.println("没找到" + strSearch);
}
输出:
请输入要查找的单词:
dog
找到了键值对为:dog-狗
请输入要查找的单词:
gu
没找到gu