package com.set;
import java.util.*;
import java.util.Map.Entry;
public class DictionaryDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,String> animal=new HashMap<String,String>();
System.out.println("请输入三组单词对应的注释,并存放到HashMap中");
Scanner input=new Scanner(System.in);
//添加数据
int i=0;
while(i<3) {
System.out.println("请输入key值(单词)");
String key=input.next();
System.out.println("请输入value值(注释)");
String value=input.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());
}
}
}
测试二##############################################################################################################################################################################################
根据已知条件将夺冠年份作为key值,冠名队名作为value值,存储至少三条数据到HashMap中,并循环打印输出。
1、将夺冠年份和冠军队名以key-value形式存储到 HashMap中
2、使用迭代器和EntrySet两种方式遍历输出HashMap中的key和value
package com.set;
import java.util.*;
import java.util.Map.Entry;
public class FootballDemo {
public static void main(String[] args) {
// 创建HashMap对象
Map<String, String> map = new HashMap<String, String>();
// 添加数据
Scanner input = new Scanner(System.in);
// 添加数据
int i = 0;
while (i < 3) {
System.out.println("请输入年份");
String key = input.next();
System.out.println("请输入国家");
String value = input.next();
map.put(key, value);
i++;
}
System.out.println("使用迭代器输出:");
Iterator<String> it = map.values().iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
// 通过entrySet方法
System.out.println("通过entrySet输出:");
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
System.out.print(entry.getKey() + "-");
System.out.println(entry.getValue());
}
}
}