import java.util.*;/**
* Map是用来存储”键/值“对的对象,再Map中存储的关键字和值都必须是对象
* 并要求关键字是唯一的,而值可以重复
* Map接口常用的实现类有HashMap,TreeMap,HashTable,LinkedHashMap
* 下面介绍HashMap类的实现
*/publicclassMapDemo{publicstaticvoidmain(String[] args){
String [] country ={"China","India","Australia","germany","Cuba","greece","Japan"};//存放国家名的数组
String [] capital ={"Beijing","New Delhi","Canberra","Berlin","Havana","Athens","Tokyo"};//存放首都名的数组
Map<String,String> m =newHashMap<>();for(int i=0; i<country.length; i++){
m.put(country[i],capital[i]);}
System.out.println("共有"+ m.size()+"个国家");
Set<String> set = m.keySet();//返回由键组成的set对象
List<String> list =newArrayList<>(set);//转换成List对象for(String s : list){
System.out.print(s +" ");//输出国家名}
System.out.println();
m.put("America","New York");//向集合中添加键值对
System.out.println(m.get("China"));//返回键China对应的值
m.remove("India");//从集合中删除指定键值对
System.out.println(m);//打印集合
System.out.println(m.containsKey("China"));//判断集合是否包含指定的键
System.out.println(m.containsValue("Beijing"));//判断集合是否包含指定的值
System.out.println(m.isEmpty());//判空操作
Collection col = m.values();//返回由值组成的Collection对象
Iterator iterator = col.iterator();while(iterator.hasNext()){//迭代器方式输出值
System.out.print(iterator.next()+" ");}}}
TreeMap类实现类SortedMap接口,保证Map中的键值对按关键字升序排列 *下面在D盘创建名为proverb的文本文件,文件内容如下: no pains, no gains. well begun is half done. where there is a will , there is a way.