package com.swift; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; public class Map_keySet_entrySet { public static void main(String[] args) { /* * TreeMap 集合存储自定义对象,并使用 2 中方式遍历获取 */ Map<Person,String> hm = new HashMap<Person, String>(); hm.put(new Person("lisi",18), "加拿大"); hm.put(new Person("zhangsa",17), "澳大利亚"); hm.put(new Person("zhangsa",17), "澳大利亚"); hm.put(new Person("wangwu",20), "新加坡"); hm.put(new Person("zhaoliu",19), "新西兰"); hm.put(new Person("zhaoliu",19), "新西兰"); hm.put(new Person("lisa",22), "迪拜"); //使用TreeMap无法排序比较是会出现Comparable异常错误 这时需要自己弄比较器 Map<Person,String> tree = new TreeMap<Person, String>(new Comparator<Person>() { @Override public int compare(Person arg0, Person arg1) { int num=arg0.getAge()-arg1.getAge(); return num==0?arg0.getName().compareTo(arg1.getName()):num; } }); tree.put(new Person("lisisi",18), "china"); //keySet方法一 Set<Person> set=hm.keySet(); for(Person per:set) { System.out.println("人员:"+per.toString()+"来自:"+hm.get(per)); } Set<Person> set1=tree.keySet(); for(Person per:set1) { System.out.println("人员:"+per.toString()+"来自:"+tree.get(per)); } //entrySet方法二 for(Map.Entry<Person, String> en:hm.entrySet()) { System.out.println(); System.out.println("人员:"+en.getKey().toString()+"来自:"+en.getValue()); } } }